给定在 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 许可协议
它失败了,因为
edges
是一种方法。文档 说要这样做:
例如,以下对我有用:
但是,您的代码类型确实失败了:
在你的情况下,我建议