如何使用networkx在加权图中找到最短路径?

10 投票
1 回答
13330 浏览
提问于 2025-04-17 13:13

我正在使用 networkx 这个库,在 Python 2.7 Enthought 版本 中计算海港网络之间的最短路径。用 dijkstra_path_length 计算距离时一切正常,但我还想知道通过 dijkstra_path 找到的具体路线(顺便说一下,我觉得先计算路径再计算长度会更快,而不是在同样的数据上运行两次 Dijkstra 算法)。不过,路径函数出错了,提示 list indices must be integers, not str

这是导致错误的代码。有人能告诉我我哪里出错了吗?

import networkx as nx

# Create graph
network_graph = nx.Graph()
f_routes = open('routes-list.txt', 'rb')
# Assign list items to variables
for line in f_routes:
    route_list = line.split(",")
    orig = route_list[0]
    dest = route_list[1]
    distance = float(route_list[2])
    # Add route as an edge to the graph
    network_graph.add_edge(orig, dest, distance=(distance))

# Loop through all destination and origin pairs
for destination in network_graph:
    for origin in network_graph:
        # This line works
        length = nx.dijkstra_path_length(network_graph, origin, destination, "distance")
        # This line fails
        path = nx.dijkstra_path(network_graph, origin, destination, "distance")

我在错误追踪中得到了以下内容。

Traceback (most recent call last):
  File "C:\Users\jamie.bull\workspace\Shipping\src\shortest_path.py", line 67, in <module>
    path = nx.dijkstra_path(network_graph, origin, destination, "distance")
  File "C:\Enthought\Python27\lib\site-packages\networkx\algorithms\shortest_paths\weighted.py", line 74, in dijkstra_path
    return path[target]
TypeError: list indices must be integers, not str

1 个回答

18

经过一些实验,发现当起点和终点是同一个节点时,nx.dijkstra_path会抛出一个让人误解的错误。

>>> import networkx as nx
>>> g = nx.Graph()
>>> g.add_edge('a', 'b', distance=0.3)
>>> g.add_edge('a', 'c', distance=0.7)
>>> nx.dijkstra_path_length(g, 'b', 'c', 'distance')
1.0
>>> nx.dijkstra_path(g, 'b', 'c', 'distance')
['b', 'a', 'c']
>>> nx.dijkstra_path_length(g, 'b', 'b', 'distance')
0
>>> nx.dijkstra_path(g, 'b', 'b', 'distance')
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    nx.dijkstra_path(g, 'b', 'b', 'distance')
  File "C:\Users\barberm\AppData\Roaming\Python\Python27\site-packages\networkx\algorithms\shortest_paths\weighted.py", line 74, in dijkstra_path
    return path[target]
TypeError: list indices must be integers, not str

所以,最好先明确检查一下destination(终点)和origin(起点)是否是同一个,如果是的话,就单独处理这种情况。

撰写回答