我有一长串构成图表的源和目标,如下所示:
id_a = [...] #source nodes
id_b = [...] #target nodes
distance = [..] #distance between source and target nodes
G = nx.Graph()
path, length = [], []
for a, b, c in zip(id_a, id_b, distance):
G.add_edge(a, b, weight=c)
cl是图中所有节点的子集,我想提取将所有cl互连在一起的路径,所以我使用all_simple_paths()
path = []
for i in range(len(cl)):
for j in range(len(cl)):
if i != j:
path.append(nx.all_simple_paths(G, source=cl[i], target=cl[j]))
我希望能够列出所有简单路径及其长度,所以我尝试:
for i in range(len(path)):
total_length = 0
for j in range(len(path[i])-1):
source, target = path[i][j], path[i][j+1]
edge = G[source][target]
length = edge['weight']
total_length += length
length.append(total_length)
但是我不断收到错误消息
object of type 'generator' has no len()
而且我不知道如何将all_simple_paths()的生成器转换为可以迭代并提取所有路径的全长的列表。
感谢您的帮助!
答案 0 :(得分:0)
如果您阅读all_simple_paths的文档,将会看到它返回了一个生成器。因此,只需使用extend
而不是像这样的append
方法
path = []
for i in range(len(cl)):
for j in range(len(cl)):
if i != j:
path.extend(nx.all_simple_paths(G, source=cl[i], target=cl[j]))
有关extend
在这种情况下为何起作用的更多信息,请参见this answer。
我还在代码的最后部分看到,您将length
设置为length = edge['weight']
,然后使用length.append(total_length)
进行追加。由于边缘权重将为int
,因此这将作为错误返回。使用类似这样的不同变量名
path_weight = [] #<----- List to store all path's weights
for i in range(len(path)):
total_length = 0
for j in range(len(path[i])-1):
source, target = path[i][j], path[i][j+1]
edge = G[source][target]
length = edge['weight'] #<--- Get the weight
total_length += length
path_weight.append(total_length) #Append to the list