2016-03-13 107 views
0

我需要一些圖形幫助。我使用模塊NetworkX,但知道它的一切並不重要。我是Python的初學者。我開始創建一個正常的圖表:使用NetworkX列表中所有路徑的長度

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) 

我加了兩個屬性:長度和SF(我將在以後需要它)。我跑了這個程序,並得到與節點1和節點3:

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

如何計算路徑的長度?而且我需要將長度乘以屬性「sf」。我簡化了這個問題,因爲後來我有數百個節點,所以它會變得更加困難。

我開始考慮函數,但我只是得到錯誤。

回答

0

你可以使用一個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 
相關問題