我正在使用networkx
包Python 2.7 Enthought distribution
来计算海港网络之间的最短路径。使用 计算距离可以正常工作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