NetworkX:如何为现有的 G.edges() 添加权重? [英] NetworkX: how to add weights to an existing G.edges()?

查看:29
本文介绍了NetworkX:如何为现有的 G.edges() 添加权重?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Given any graph G created in NetworkX, I want to be able to assign some weights to G.edges() after the graph is created. The graphs involved are grids, erdos-reyni, barabasi-albert, and so forth.

鉴于我的G.edges():

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

还有我的权重:

{(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.

How can I assign each edge the relevant weight? In this trivial case all weights are 1.

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

I've tried to add the weights to G.edges() directly like this

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() 是一个列表,为什么我不能像访问任何其他列表一样访问它的元素?

What's wrong? Since G.edges() is a list, why can't I access its elements as with any other list?

推荐答案

失败,因为 edges 是一个方法.

It fails because edges is a method.

文档 说要这样做喜欢:

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}

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

However, your type of code indeed fails:

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__'

<小时>

在你的情况下,我建议


In your case, I'd suggest

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

这篇关于NetworkX:如何为现有的 G.edges() 添加权重?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆