NetworkX:如何为现有的 G.edges() 添加权重?

新手上路,请多包涵

给定在 NetworkX 中创建的任何图 G,我希望能够在创建图 为 G.edges() 分配一些权重。涉及的图有grids、erdos-reyni、barabasi-albert等。

鉴于我的 G.edges()

 [(0, 1), (0, 10), (1, 11), (1, 2), (2, 3), (2, 12), ...]

还有我的 weights

 {(0,1):1.0, (0,10):1.0, (1,2):1.0, (1,11):1.0, (2,3):1.0, (2,12):1.0, ...}

如何为每条边分配相关权重? 在这个简单的例子中,所有的权重都是 1。

我试过像这样直接将权重添加到 G.edges()

 for i, edge in enumerate(G.edges()):
    G.edges[i]['weight']=weights[edge]

但我收到此错误:

 ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-48-6119dc6b7af0> in <module>()
     10
     11 for i, edge in enumerate(G.edges()):
---> 12     G.edges[i]['weight']=weights[edge]

TypeError: 'instancemethod' object has no attribute '__getitem__'

怎么了? 由于 G.edges() 是一个列表,为什么我不能像访问任何其他列表一样访问它的元素?

原文由 FaCoffee 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.6k
2 个回答

它失败了,因为 edges 是一种方法。

文档 说要这样做:

 G[source][target]['weight'] = weight

例如,以下对我有用:

 import networkx as nx

G = nx.Graph()

G.add_path([0, 1, 2, 3])

G[0][1]['weight'] = 3

>>> G.get_edge_data(0, 1)
{'weight': 3}

但是,您的代码类型确实失败了:

 G.edges[0][1]['weight'] = 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-97b10ad2279a> in <module>()
----> 1 G.edges[0][1]['weight'] = 3

TypeError: 'instancemethod' object has no attribute '__getitem__'


在你的情况下,我建议

for e in G.edges():
    G[e[0]][e[1]] = weights[e]

原文由 Ami Tavory 发布,翻译遵循 CC BY-SA 3.0 许可协议

文档

  • 您可以一次将所有边缘权重设置为相同的值
nx.set_edge_attributes(G, values = 1, name = 'weight')

  • 给定一个字典,其中的键对应于边元组(您的 weights ),您可以将边权重分配给该字典中的值
nx.set_edge_attributes(G, values = weights, name = 'weight')

  • 查看并验证是否已设置这些边缘属性
G.edges(data = True)

原文由 rlchqrd 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题