如何在Networkx中指定边长以计算最短距离? [英] How to specify edge length in Networkx for calculating shortest distance?
问题描述
我有节点和边的列表,但我希望某些边的长度为2,而不是1.因此,当使用内置算法计算节点之间的距离时,它将返回
I have a list of nodes and edges but I want some edges to be of length two instead of one. So when the distance between the nodes is calculated using the built in algorithm it returns
例如,如果我以(1、2),(2 *,3),(4 *,5)作为节点之间的边,其中带有星号的节点之间的距离为长度2,则( 1、2)应该是1,(2,3)应该是2而不是1,然后(1,5)之间的距离应该是5而不是3.
For example, if I have (1, 2), (2*, 3), (4*, 5) as edges between nodes, where the distance between the nodes with an asterisk have length two, the distance between (1, 2) should be 1, (2,3) should be 2 instead of 1 and then the distance between (1,5) should be 5 instead of 3.
添加节点时,我尝试了G.add_edge(4,5,length=2)
,但nx.shortest_path_length(G,source=4,target=5))
仍然返回1而不是2.如何指定边缘长度?
When adding nodes I've tried G.add_edge(4,5,length=2)
but nx.shortest_path_length(G,source=4,target=5))
still returns 1 instead of two. How can I specify edge length?
推荐答案
您需要在边缘上附加一个length
属性,然后指定查找最短路径时要按这些长度进行加权:>
You need to have a length
attribute attached to your edges, and then specify that you want to weight by those lengths when finding the shortest path:
# Had to add an edge from 3 to 4 to your example edges
# or there's no path from 1 to 5
edges = [(1, 2, 1), (2, 3, 2), (3, 4, 1), (4, 5, 2)]
G = networkx.Graph()
for start, end, length in edges:
# You can attach any attributes you want when adding the edge
G.add_edge(start, end, length=length)
networkx.shortest_path_length(G, 1, 5, weight='length')
Out[8]: 6
这篇关于如何在Networkx中指定边长以计算最短距离?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!