更改Networkx Multigraph中的边属性 [英] Changing edge attributes in networkx multigraph

查看:692
本文介绍了更改Networkx Multigraph中的边属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多图中,每次对* add_edge(a,b,weight = 1)*的调用都会在节点 a b 之间添加新边.构建图形时,可以在再次找到 a b 时修改此权重.现在,我进行检查以查找(a,b)或(b,a)是否已连接,然后必须删除边缘,并 add 一个新的边缘.在我看来,我应该可以轻松更新体重.

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.

注意:我确实需要多图,因为我在节点之间使用不同类型的边(使用 key 进行区分)

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

推荐答案

Multigraph.add_edge 文档指示您应使用key参数来唯一标识多图中的边.这是一个示例:

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})]

现在,要更新由xyz键控的边,只需再次传入该参数即可:

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})]

要读取先前的值,可以使用 get_edge_data 像这样:

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

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

这篇关于更改Networkx Multigraph中的边属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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