【发布时间】:2020-04-19 21:47:11
【问题描述】:
所以我试图创建一个代码来使用 Networkx 查找子路径的最短路径长度,基本上我的代码所做的是它需要一个 3D 数组来创建图形,然后将它们保存在一个列表中,以便我可以使用此列表使用 networkx 查找 the shortest path 和 the shortest path length。
然后,根据列表中的信息,我想在图中找到一个子路径的最短路径长度,如果一个路径的len小于等于3,那么最短路径在相同的源节点和目标节点(所以长度将为零),如果len 大于那个,那么它应该在路径中的第二个节点和倒数第二个节点之间找到shortest path length(类似于“路径的中心”),我的代码在下面
import networkx as nx
import numpy as np
arr= np.array([[[ 0., 191., 16., 17., 15., 18., 18.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 141., 0., 0., 0., 18., 0.],
[ 0., 138., 0., 0., 0., 0., 19.],
[ 0., 80., 0., 0., 0., 0., 15.],
[ 0., 130., 11., 0., 0., 0., 19.],
[ 0., 135., 0., 12., 16., 12., 0.]],
[[ 0., 156., 17., 13., 19., 10., 11.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 21., 0., 0., 0., 6., 0.],
[ 0., 147., 0., 0., 0., 0., 4.],
[ 0., 143., 0., 0., 0., 0., 6.],
[ 0., 69., 4., 0., 0., 0., 7.],
[ 0., 87., 0., 1., 5., 9., 0.]],
[[ 0., 161., 18., 16., 13., 13., 17.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 138., 0., 0., 0., 21., 0.],
[ 0., 64., 0., 0., 0., 0., 29.],
[ 0., 23., 0., 0., 0., 0., 29.],
[ 0., 2., 24., 0., 0., 0., 27.],
[ 0., 61., 0., 24., 29., 26., 0.]],
[[ 0., 163., 12., 13., 17., 19., 13.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 142., 0., 0., 0., 35., 0.],
[ 0., 122., 0., 0., 0., 0., 31.],
[ 0., 72., 0., 0., 0., 0., 36.],
[ 0., 50., 39., 0., 0., 0., 31.],
[ 0., 4., 0., 38., 39., 35., 0.]],
[[ 0., 180., 17., 19., 13., 18., 15.],
[ 0., 0., 0., 0., 0., 0., 0.],
[ 0., 44., 0., 0., 0., 46., 0.],
[ 0., 27., 0., 0., 0., 0., 47.],
[ 0., 81., 0., 0., 0., 0., 45.],
[ 0., 116., 48., 0., 0., 0., 45.],
[ 0., 16., 0., 42., 49., 49., 0.]]])
graphs= []
paths = []
pathlenght = []
aux = []
for i in arr :
graphs.append(nx.from_numpy_array(i, create_using = nx.DiGraph)) #List of graphs created by the 3D array
for j in graphs:
paths.append(nx.shortest_path(j, 0, 1, weight = 'weight')) #Shortest paths of every graph
pathlenght.append(nx.shortest_path_length(j, 0, 1, weight = 'weight')) #Shortest path length of every graphs
for i in graphs:
for j in paths:
if len(j) <= 3:
aux.append(nx.shortest_path_length(i, j[0], j[0], weight = 'weight'))
else:
aux.append(nx.shortest_path_length(i, j[1], j[-2], weight = 'weight'))
print(paths) # [[0, 4, 1], [0, 5, 2, 1], [0, 5, 1], [0, 6, 1], [0, 6, 1]]
print(pathlenght) # [95.0, 35.0, 15.0, 17.0, 31.0]
print(aux) #[ 0. 11. 0. 0. 0. 0. 4. 0. 0. 0. 0. 24. 0. 0. 0. 0. 39. 0. 0. 0. 0. 48. 0. 0. 0.] shape = (25,)
路径和路径长度很好,但在辅助列表中我期望输出是
#aux = [0, 4.0, 0, 0, 0]
我知道问题出在双 for-loop 因为有 5 个图形和 5 个路径,辅助列表有 25 个元素,但我想使用与他的图形相符的路径(路径 1 与图形 1,路径 2图 2 等等)所以aux 的输出将与上面相同。
我有点新使用for-loop 所以我希望你能帮助我,或者如果有另一种方法可以做我想要实现的目标,任何帮助将不胜感激,谢谢!
【问题讨论】: