Changing edge attributes in networkx multigraph

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

In a multigraph each call to *add_edge(a,b,weight=1)* will add a new edge between nodes a and b. When building the graph, is it possible to modify this weight when a and b are found again. Right now I make a check to find whether (a, b) or (b, a) are connected, then have to delete the edge, and add a new one. It seems to me that I should simply be able to update the weight.

Note: I do need multigraphs because I use different types of edges between nodes (differentiated using key)

回答1:

The Multigraph.add_edge documentation indicates that you should use the key argument to uniquely identify edges in a multigraph. Here's an example:

>>> import networkx as nx >>> G = nx.MultiGraph() >>> G.add_edge(1, 2, key='xyz', weight=2) >>> G.add_edge(1, 2, key='abc', weight=1) >>> G.edges(data=True) [(1, 2, {'weight': 2}), (1, 2, {'weight': 1})] 

Now, to update the edge keyed by xyz, just pass that parameter in again:

>>> G.add_edge(1, 2, key='xyz', weight=7) >>> G.edges(data=True) [(1, 2, {'weight': 7}), (1, 2, {'weight': 1})] 

To read the previous value, you can use get_edge_data like this:

>>> G.get_edge_data(1, 2, key='xyz') {'weight': 7} 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!