[英]join subgraphs with networkx
通過以前的程序,我得到類似這些的條目,有沒有辦法在for中做這個句子? 城市的價值有兩個清單,一個是起源,第二個是命運。
path_1=G.subgraph(nx.shortest_path(G,"Chicago","Houston"))
path_2=G.subgraph(nx.shortest_path(G,"Chicago","Dallas"))
path_3=G.subgraph(nx.shortest_path(G,"Chicago","LosAngeles"))
path_4=G.subgraph(nx.shortest_path(G,"Chicago","Miami"))
path_5=G.subgraph(nx.shortest_path(G,"Chicago","NewYork"))
path_6=G.subgraph(nx.shortest_path(G,"Dallas","LosAngeles"))
path_7=G.subgraph(nx.shortest_path(G,"Houston","NewYork"))
paths=nx.compose(path_1,path_2)
paths_2=nx.compose(paths,path_3)
paths_3=nx.compose(paths_2,path_4)
paths_4=nx.compose(paths_3,path_5)
paths_5=nx.compose(paths_4,path_6)
paths_6=nx.compose(paths_5,path_7)
nx.draw_networkx(paths_6)
我試過了,但它不正確,我對 path3 感到困惑
for i in range (0,len(o),2):
path1=G.subgraph(nx.shortest_path(G,o[i],d[i]))
if o[i+1]==o[-1]:
path2=G.subgraph(nx.shortest_path(G,o[i+1],d[i+1]))
else:
break
if o[i+2]==o[-1]:
path3=G.subgraph(nx.shortest_path(G,o[i+2],d[i+2]))
z=nx.compose(path1,path2)
zz=nx.compose(z,path3)
else:
break
nx.draw_networkx(zz)
沒用過這個庫,但是IIUC,可以這樣寫:
from functools import reduce
# sample lists
origins = ['Chicago', 'Chicago', 'Chicago']
dests = ['Houston', 'Dallas', 'LosAngeles']
# function returning subgraph object for one pair of origin and destination
def gen_subgraph(G, origin, dest):
return G.subgraph(nx.shortest_path(G, origin, dest))
# create a list of all necessary subgraph objects
path_list = []
for o, d in zip(origins, dests):
path_list.append(gen_subgraph(G, o, d))
# function creating complete nx.compose() object by applying the
# nx.compose function cumulatively to elements of path_list
def compose_cumulatively(path_list):
return reduce(nx.compose, path_list)
# produce final result by calling the function above
nx.draw_networks(compose_cumulatively(path_list))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.