Skip to main content
 首页 » 编程设计

python之计算图中节点距离时的关键错误

2024年10月25日9zhengyun_ustc

我一直收到这个关键错误,但我不明白这是怎么回事。我使用的是 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'  

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

请您参考如下方法:

并非所有图节点都与所有其他图节点有边,因此使用 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 对于节点之间的距离通常设置为无穷大