我在Python中有一个networkx图,带有加权边。我想得到两个节点之间最小路径的权重。在
目前,我正在从nx.最短路径实现,然后迭代每对节点并对每对节点之间的权重求和。在
shortest_path = nx.shortest_path(G, source, destination, 'distance')
#function to iterate over each pair
import itertools
def pairwise(iterable):
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
weightSum = 0
for adjPair in pairwise(shortest_path):
weightSum = weightSum + G[adjPair[0]][adjPair[1]]['distance']
有没有更好的(内置的)替代方案?在
networkx文档有以下页面:shortest paths。在
有几个选项,但看起来
shortest_path_length()
就是您想要的。在为了清楚起见:
你在找^{} :
示例
^{pr2}$输出
相关问题 更多 >
编程相关推荐