【发布时间】:2021-02-08 14:52:00
【问题描述】:
我有一个这样的相对节点和边图:
我想要的是找到一种方法来仅对我列表中包含的节点执行 networkx 的最短路径,即:
source = ["10.0.11.100","10.0.12.100","10.0.13.100","10.0.14.100"]
destination = ["10.0.11.100","10.0.12.100","10.0.13.100","10.0.14.100"]
我不想手动做这个,即:
nx.shortest_path(G, source="10.0.11.100", target="10.0.12.100")
nx.shortest_path(G, source="10.0.11.100", target="10.0.13.100")
nx.shortest_path(G, source="10.0.11.100", target="10.0.14.100")
nx.shortest_path(G, source="10.0.12.100", target="10.0.11.100")
nx.shortest_path(G, source="10.0.12.100", target="10.0.13.100")
nx.shortest_path(G, source="10.0.12.100", target="10.0.14.100")
...
我想要的结果是这样的:
[('10.0.12.100','10.0.14.100',['10.0.1.11', '10.0.1.23']), ('10.0.14.100', '10.0.12.100', ['10.0.1.22', '10.0.1.9']), ('10.0.11.100', '10.0.14.100', ['10.0.1.6', '10.0.1.18', '10.0.1.26']), ('10.0.14.100', '10.0.11.100' ,['10.0.1.25', '10.0.1.17', '10.0.1.5'])...]
即[(Source, Destination, [Path from Source to Destination])]
有没有办法做到这一点?非常感谢
这是我的代码:
import networkx
G = nx.DiGraph()
z = [('10.0.12.100', '10.0.1.1'),('10.0.1.1', '10.0.11.100'),('10.0.11.100', '10.0.1.2'),('10.0.1.2', '10.0.12.100'),('10.0.13.100', '10.0.1.17'),('10.0.1.17', '10.0.1.5'),('10.0.1.5', '10.0.11.100'),('10.0.11.100', '10.0.1.6'),('10.0.1.6', '10.0.1.18'),('10.0.1.18', '10.0.13.100'),('10.0.11.100', '10.0.1.6'),('10.0.1.6', '10.0.1.18'),('10.0.1.18', '10.0.1.26'),('10.0.1.26', '10.0.14.100'),('10.0.14.100', '10.0.1.22'),('10.0.1.22', '10.0.1.9'),('10.0.1.9', '10.0.12.100'),('10.0.12.100', '10.0.1.1'),('10.0.1.1', '10.0.1.6'),('10.0.1.6', '10.0.1.18'),('10.0.1.18', '10.0.13.100'),('10.0.13.100', '10.0.1.26'),('10.0.1.26', '10.0.14.100'),('10.0.13.100', '10.0.1.17'),('10.0.1.17', '10.0.1.5'),('10.0.1.5', '10.0.1.2'),('10.0.1.2', '10.0.12.100'),('10.0.14.100', '10.0.1.25'),('10.0.1.25', '10.0.1.17'),('10.0.1.17', '10.0.1.5'),('10.0.1.5', '10.0.11.100'),('10.0.12.100', '10.0.1.11'),('10.0.1.11', '10.0.1.23'),('10.0.1.23', '10.0.14.100'),('10.0.14.100', '10.0.1.25'),('10.0.1.25', '10.0.13.100')]
G.add_edges_from(z)
random_pos = nx.random_layout(G, seed=42)
pos=nx.spring_layout(G, pos=random_pos)
nx.draw(
G,
pos=pos,
node_color='#FF0000',
with_labels=True,
arrows=False
)
source = ["10.0.11.100","10.0.12.100","10.0.13.100","10.0.14.100"]
destination = ["10.0.11.100","10.0.12.100","10.0.13.100","10.0.14.100"]
list_shortest_path = []
for i in G.nodes(data=True):
DD = list_shortest_path.append(nx.shortest_path(G, source=i[0], target=i[1]))
【问题讨论】:
标签: python python-3.x list graph networkx