python networkx进行最短路径分析_如何利用networkx在加权图中寻找最短路径?

我正在使用Python 2.7 Enthought distribution中的networkx包计算海港网络之间的最短路径。使用dijkstra_path_length计算距离是可行的,但是我还需要知道它使用dijkstra_path找到了什么路径(另外,我认为如果我先计算路径,然后计算路径的长度,而不是在同一数据上运行Dijkstra的算法两次,运行起来应该更快)。然而,path函数失败了,说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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值