Python 在计算图中的节点距离时出现关键错误
我一直在犯这个关键错误,我不明白怎么会这样。我在语句中使用for,因此键肯定存在:Python 在计算图中的节点距离时出现关键错误,python,dictionary,graph,nodes,floyd-warshall,Python,Dictionary,Graph,Nodes,Floyd Warshall,我一直在犯这个关键错误,我不明白怎么会这样。我在语句中使用for,因此键肯定存在: 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() pr
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
将导致关键点错误
也许你想要这样的东西:
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)
对于节点之间的距离,
默认值
通常设置为无穷大这看起来像是我期望的行为。您的图形字典不是一个完整的矩阵。例如,图[1]不包含键3
当图形[n][m]不包含从n到m的边时,看起来您希望有一个默认的无穷大值。您可以通过进行显式检查或使用