为什么我的所有边都在 networkx 有向图中分配了相同的值?

问题描述

我已经被这个简单的问题困住了一段时间,无法弄清楚解决方案。我有一本名为 EdgeDictFull 的字典,其结构类似于 {(node1,node2): weight}。我想创建一个有向图,将权重存储为图中的一个属性。我尝试了一大堆不同的想法,但似乎都没有奏效。当我运行此代码时....

(权重只是我想作为属性添加到边的所有权重的列表)

TG = nx.DiGraph()
for x in weights:
    TG.add_edges_from(EdgeDictFull.keys(),weight = x)

TG.edges(data = True)

这将创建所有正确的边,但所有边都将具有我的权重列表中最后一个整数的属性值。我想我明白它为什么会这样做,但是,我似乎无法弄清楚如何解决它。我知道这很简单。任何建议都会很棒!

解决方法

# the problem with your code is that in every iteration of your loop you add
# *all* edges,and all of them get the same weight.

# you can do either of  the following:

# zip:
TG = nx.DiGraph()
for edge,weight in zip(EdgeDictFull.keys(),weights):
    TG.add_edge(*edge,weight=weight)
    
# or directly work with the dictionary:    
## dummy dictionary:
EdgeDictFull = {(np.random.randint(5),np.random.randint(5)):np.random.rand() for i in range(3)}

TG = nx.DiGraph()
TG.add_weighted_edges_from((a,b,c) for (a,b),c in EdgeDictFull.items())
    
    
TG.edges(data = True)