【问题标题】:Key Error when computing node distances in graph计算图中节点距离时的关键错误
【发布时间】:2015-05-04 20:48:36
【问题描述】:

我不断收到这个关键错误,但我不明白怎么回事。我使用的是 for-in 语句,所以键肯定存在:

def floydWarshall(inFile):
    graph = readGraph(inFile)
    print(graph) # = {'0': {'1': 28, '3': 33}, '2': {'3': 50}, '1': {'4': 44, '2': 10}, '3': {'4': 30}, '4': 999999999}
    nodes = graph.keys()
    print(nodes) # = dict_keys(['0', '2', '1', '3', '4'])

    distance = {}

    for n in nodes:
        distance[n] = {}

        for k in nodes:
        distance[n][k] = graph[n][k]

    for k in nodes:
        for i in nodes:
            for j in nodes:
                distance[i][j] = min (distance[i][j], distance[i][k] + distance[k][j])
    printSolution(distance)

错误:

Traceback (most recent call last):
File "C:/Users/.../prob1.py", line 58, in floydWarshall
    distance[n][k] = graph[n][k]
KeyError: '2' 

关键错误只是在节点中首先出现的任何键上,每次都会更改

【问题讨论】:

    标签: python dictionary graph nodes floyd-warshall


    【解决方案1】:

    并非所有图节点都与所有其他图节点有边,因此使用 graph[n][k] 遍历整个图上的所有节点 k 将导致 KeyError。

    也许你想要类似的东西:

    for n in nodes:
        distance[n] = {}
    
        for k in graph[n]: 
            distance[n][k] = graph[n][k]
    

    或者,如果你想在边缘不存在的情况下将 distance[n][k] 设置为某个默认值:

    for n in nodes:
        distance[n] = {}
    
        for k in nodes: 
            distance[n][k] = graph[n].get(k, default_value)
    

    default_value 对于节点之间的距离通常设置为无穷大

    【讨论】:

      【解决方案2】:

      这对我来说似乎是预期的行为。您的图形字典不是一个完整的矩阵。例如,graph[1] 不包含键 3。

      当 graph[n][m] 不包含从 n 到 m 的边时,您似乎想要一个默认的无穷大值。您可以通过显式检查或使用defaultdict 来做到这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-31
        • 1970-01-01
        • 1970-01-01
        • 2017-04-02
        • 1970-01-01
        • 2021-11-03
        • 2013-03-31
        相关资源
        最近更新 更多