使用NetworkX的列表中所有路径的长度

时间:2016-03-13 20:54:54

标签: python

我需要一些Graph的帮助。我使用的是NetworkX模块,但了解它的一切并不是那么重要。我是Python的初学者。我开始创建一个普通的Graph:

import networkx as nx

G = nx.Graph()

G.add_edge("Node1","Node2",length=140,sf=4)
G.add_edge("Node2","Node3",length=170,sf=3)
G.add_edge("Node1","Node4",length=300,sf=1)
G.add_edge("Node4","Node3",length=230,sf=10)

x = input('First Node: ')
y = input('Second Node: ')

paths = sorted(nx.all_simple_paths(G,x,y))

print(paths)

我添加了2个属性:length和sf(稍后我将需要它)。我运行这个程序并使用Node1和Node3:

[['Node1', 'Node2', 'Node3'], ['Node1', 'Node4', 'Node3']]

如何计算路径的长度?而且我需要将长度乘以属性“sf”。我简化了问题,因为后来我有数百个节点,所以它会更难。

我开始考虑使用for-function,但我只是出错了。

1 个答案:

答案 0 :(得分:1)

您可以使用for-loop

import sys
import networkx as nx

G = nx.Graph()

G.add_edge("Node1", "Node2", length=140, sf=4)
G.add_edge("Node2", "Node3", length=170, sf=3)
G.add_edge("Node1", "Node4", length=300, sf=1)
G.add_edge("Node4", "Node3", length=230, sf=10)

x, y = sys.argv[-2:]
paths = sorted(nx.all_simple_paths(G, x, y))

for path in paths:
    total_length = 0
    for i in range(len(path)-1):
        source, target = path[i], path[i+1]
        edge = G[source][target]
        length = edge['length']*edge['sf']
        total_length += length
    print('{}: {}'.format(path, total_length))

或更简洁地说,您可以用generator expression替换内部for-loop

import operator
length_sf = operator.itemgetter('length', 'sf')
for path in paths:
    total_length = sum(operator.mul(*length_sf(G[path[i]][path[i+1]])) 
                       for i in range(len(path)-1)) 
    print('{}: {}'.format(path, total_length))

两个选项都会产生(x, y = 'Node1', 'Node3'

['Node1', 'Node2', 'Node3']: 1070
['Node1', 'Node4', 'Node3']: 2600