如何提取并存储NetworkX shortest_path函数生成的所有最短路径列表
实现方法
nx.all_pairs_shortest_path()返回的迭代器中,每个元素的第二个值是存储「目标节点:对应最短路径」的字典,直接提取所有字典的value值合并即可得到所有路径列表。
完整可运行代码
import networkx as nx G2 = nx.DiGraph() G2.add_edges_from([('A','B'),('A','C'),('F','G'),('A','F'),('F','H'),('A','I')]) # 计算所有节点对的最短路径 paths = nx.all_pairs_shortest_path(G2) # 收集所有路径 all_path_list = [] for source, target_path_map in paths: all_path_list.extend(target_path_map.values()) # 打印验证结果 print(all_path_list)
输出结果
运行后all_path_list的内容如下:
[['A'], ['A', 'B'], ['A', 'C'], ['A', 'F'], ['A', 'I'], ['A', 'F', 'G'], ['A', 'F', 'H'], ['B'], ['C'], ['F'], ['F', 'G'], ['F', 'H'], ['G'], ['H'], ['I']]
如果需要过滤掉仅包含单个节点的自环路径,可以在收集时加判断:
all_path_list = [] for source, target_path_map in paths: for path in target_path_map.values(): if len(path) > 1: all_path_list.append(path)
过滤后的结果就会只保留多节点路径:[['A', 'B'], ['A', 'C'], ['A', 'F'], ['A', 'I'], ['A', 'F', 'G'], ['A', 'F', 'H'], ['F', 'G'], ['F', 'H']]
内容的提问来源于stack exchange,提问作者Pedram3
相关产品推荐
相关产品推荐

