[英]How to only get the shortest path with networkx (shortest_path)
[英]how to have access to lists generated through networkx shortest path function
考慮下面的代碼:
G2 = nx.DiGraph()
G2.add_edges_from([('A','B'),('A','C'),('F','G'),('A','F'),('F','H'),('A','I')])
nx.draw(G2, with_labels=1)
paths = (nx.all_pairs_shortest_path(G2))
for path in paths :
print(path)
此代碼的 output 是:
('A', {'A': ['A'], 'B': ['A', 'B'], 'C': ['A', 'C'], 'F': ['A', 'F'], 'I': ['A', 'I'], 'G': ['A', 'F', 'G'], 'H': ['A', 'F', 'H']})
('B', {'B': ['B']})
('C', {'C': ['C']})
('F', {'F': ['F'], 'G': ['F', 'G'], 'H': ['F', 'H']})
('G', {'G': ['G']})
('H', {'H': ['H']})
('I', {'I': ['I']})
我想知道如何訪問所有列表,例如 ['A']、['A'、'B']、['A'、'C']、['A'、'F'] , ... 並將它們存儲在列表中。
謝謝你。
paths
是一個生成器。 它不支持項目分配。 您可能希望將其轉換為執行此操作的數據結構:
d = dict(paths)
>>> print(d)
{'A': {'A': ['A'], 'B': ['A', 'B'], 'C': ['A', 'C'], 'F': ['A', 'F'], 'I': ['A', 'I'], 'G': ['A', 'F', 'G'], 'H': ['A', 'F', 'H']}, 'B': {'B': ['B']}, 'C': {'C': ['C']}, 'F': {'F': ['F'], 'G': ['F', 'G'], 'H': ['F', 'H']}, 'G': {'G': ['G']}, 'H': {'H': ['H']}, 'I': {'I': ['I']}}
這不是很有代表性。 但是,您仍然可以檢查特定的邊緣,例如:
>>> d['A']['H']
['A', 'F', 'H']
我們也可以稍微整理一下,讓所有可能的路徑遍歷:
from itertools import product
>>> print(list(product(d.keys(), repeat=2)))
[('A', 'A'), ('A', 'B'), ('A', 'C'), ..., ('I', 'G'), ('I', 'H'), ('I', 'I')]
dd = {(a, b): d[a][b] for a, b in product(d.keys(), repeat=2) if b in d[a]}
>>> dd
{('A', 'A'): ['A'],
('A', 'B'): ['A', 'B'],
('A', 'C'): ['A', 'C'],
('A', 'F'): ['A', 'F'],
('A', 'G'): ['A', 'F', 'G'],
('A', 'H'): ['A', 'F', 'H'],
('A', 'I'): ['A', 'I'],
('B', 'B'): ['B'],
('C', 'C'): ['C'],
('F', 'F'): ['F'],
('F', 'G'): ['F', 'G'],
('F', 'H'): ['F', 'H'],
('G', 'G'): ['G'],
('H', 'H'): ['H'],
('I', 'I'): ['I']}
它可以以稍微不同的方式使用:
>>> dd['A', 'H']
['A', 'F', 'H']
或者,沒有itertools
:
dd = {(a, b): d[a][b] for a in d.keys() for b in d.keys() if b in d[a]}
Output 應該是一樣的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.