2017-02-27 58 views
1

我試圖運行這一點,我越來越有記憶address.How最短路徑,我可以從輸出Python - 如何從這個networkx代碼中提取所有最短路徑?

import networkx as nx 
G=nx.Graph() 
G.add_nodes_from([1,2,3,4]) 
G.add_weighted_edges_from([(1,2,8),(1,3,5),(2,4,1),(3,4,2)]) 
print(nx.floyd_warshall(G)) 

這裏取下內存地址是輸出

{1: defaultdict(<function floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda> at 0x000002AA0C397B70>, {1: 0, 2: 8, 3: 5, 4: 7}), 
`2: defaultdict(<function floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda> at 0x000002AA0D96A378>, {1: 8, 2: 0, 3: 3, 4: 1}), 
3: defaultdict(<function floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda> at 0x000002425C098F28>, {1: 5, 2: 3, 3: 0, 4: 2}), 
4: defaultdict(<function floyd_warshall_predecessor_and_distance.<locals>.<lambda>.<locals>.<lambda> at 0x000002425C0A2048>, {1: 7, 2: 1, 3: 2, 4: 0})} 

,我要的是輸出像這個 -

1:{1:0, 2:8, 3:5, 4:7} 
2:{1:8, 2:0, 3:3, 4:1} 
3:{1:5, 2:3, 3:0, 4:2} 
4:{1:7, 2:1, 3:2, 4:0} 

回答

0

看起來就像是一個字典裏的字典:

你可以做這樣的事情:

data = nx.floyd_warshall(G) 

for key, value in data.iteritems(): 
    print('%s %s' % (key, value.values())) 

或者,如果你想要的關鍵字:值對:

import json 

data = nx.floyd_warshall(G) 

for key, value in data.iteritems(): 
    print('%s %s' % (key, json.dumps(value))) 
0

它打印出defaultdicts的字典(這是什麼networkx收益),但你想要它打印一個字典的字典,所以你需要convert those defaultdicts into dicts

X = nx.floyd_warshall(G) 
Y = {a:dict(b) for a,b in X.items()} 
print(Y) 
> {1: {1: 0, 2: 8, 3: 5, 4: 7}, 
2: {1: 8, 2: 0, 3: 3, 4: 1}, 
3: {1: 5, 2: 3, 3: 0, 4: 2}, 
4: {1: 7, 2: 1, 3: 2, 4: 0}} 
+0

感謝Joel的回答。 –