FaC*_*fee 4 python algorithm graph edges networkx
给定在NetworkX中创建的任何图形G,我希望能够在创建图形后为G.edges()分配一些权重。涉及的图形是网格,erdos-reyni,barabasi-albert等。
鉴于我G.edges():
[(0, 1), (0, 10), (1, 11), (1, 2), (2, 3), (2, 12), ...]
Run Code Online (Sandbox Code Playgroud)
而我的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, ...}
Run Code Online (Sandbox Code Playgroud)
如何为每个边缘分配相关权重?在这种情况下,所有权重均为1。
我试图像这样直接将权重添加到G.edges()
for i, edge in enumerate(G.edges()):
G.edges[i]['weight']=weights[edge]
Run Code Online (Sandbox Code Playgroud)
但是我得到这个错误:
---------------------------------------------------------------------------
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__'
Run Code Online (Sandbox Code Playgroud)
怎么了?既然G.edges()是列表,为什么不能像其他列表一样访问其元素?
它失败,因为edges是一种方法。
该文档说要这样做:
G[source][target]['weight'] = weight
Run Code Online (Sandbox Code Playgroud)
例如,以下内容对我有用:
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}
Run Code Online (Sandbox Code Playgroud)
但是,您的代码类型确实失败了:
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__'
Run Code Online (Sandbox Code Playgroud)
就您而言,我建议
for e in G.edges():
G[e[0]][e[1]] = weights[e]
Run Code Online (Sandbox Code Playgroud)
从文档:
nx.set_edge_attributes(G, values = 1, name = 'weight')
Run Code Online (Sandbox Code Playgroud)
weights),您可以将边权重分配给该字典中的值nx.set_edge_attributes(G, values = weights, name = 'weight')
Run Code Online (Sandbox Code Playgroud)
G.edges(data = True)
Run Code Online (Sandbox Code Playgroud)