我试图给每个边分配长度属性,并根据这些长度计算从节点X到节点Y的最短路径
但是,我不确定如何正确引用我在这部分代码中指定的长度属性:nx.shortest_path(G,source='Dehli',target='Pune', weight = ?????)
import matplotlib.pyplot as plt
G = nx.Graph()
G.add_nodes_from(["Dehli","Ahmadabad","Kolkata",'Bangalore','Pune','Maduraj'])
G.add_edge('Dehli', 'Ahmadabad', length =890)
G.add_edge('Dehli', 'Kolkata', length =1422)
G.add_edge('Dehli', 'Bangalore', length =2168)
G.add_edge('Dehli', 'Pune', length =1450)
G.add_edge('Dehli', 'Maduraj', length = 2603)
G.add_edge('Ahmadabad', 'Kolkata', length =1902)
G.add_edge('Ahmadabad', 'Bangalore', length =1403)
G.add_edge('Ahmadabad', 'Pune', length =624)
G.add_edge('Ahmadabad', 'Maduraj', length =1807)
G.add_edge('Kolkata', 'Bangalore', length =1778)
G.add_edge('Kolkata', 'Pune', length =1782)
G.add_edge('Kolkata', 'Maduraj', length =2043)
G.add_edge('Bangalore', 'Pune', length =824)
G.add_edge('Bangalore', 'Maduraj', length =404)
G.add_edge('Pune', 'Maduraj', length =1195)
nx.draw(G,pos,node_color='k')
path = nx.shortest_path(G,source='Dehli',target='Pune')
path_edges = zip(path,path[1:])
nx.draw_networkx_nodes(G,pos,nodelist=path,node_color='g')
nx.draw_networkx_edges(G,pos,edgelist=path_edges,edge_color='g',width=7)
print(nx.shortest_path_length(G,source='Dehli',target='Pune'))
plt.show()
从documentation开始,对
shortest_path
的调用形式为shortest_path(G, source=None, target=None, weight=None)
可选参数
weight
是所以在你的例子中,称之为
path = nx.shortest_path(G,source='Dehli',target='Pune', weight='length')
。请注意,Networkx接受edge属性length=X
,并将其存储在一个字典中,其键为'length'
(字符串)和值为X
。在相关问题 更多 >
编程相关推荐