我不断收到此关键错误,但我不明白这是怎么回事。我使用的是 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]
或者,如果您想在边缘不存在的情况下将距离[n][k]设置为某个默认值:
for n in nodes:
distance[n] = {}
for k in nodes:
distance[n][k] = graph[n].get(k, default_value)
default_value
通常将节点之间的距离设置为无穷大
关于python - 计算图中节点距离时的关键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28844727/