首页 > 解决方案 > 如何添加具有现有边缘属性的边缘?

问题描述

如果它们具有特定属性,我正在尝试创建边缘的反向副本,如下所示:

for i in list(G.edges(data=True, keys=True)):
    if i[3]['DIRECTIONA'] == 'bothDirections':
        G.add_edge(i[1],i[0],attr_dict=i[3])

上面的内容很不方便,属性是不同的格式,而不是一个简单的属性字典,这个字典现在位于另一个字典中,键为“attr_dict”。有没有办法简单地拥有属性字典而不将它放在另一个字典中?由于格式不同,它使已经编写的代码无法工作,谢谢。

标签: pythonnetworkxgraph-theory

解决方案


您需要将边缘属性作为多个关键字参数提供(通常在函数签名中表示为**kwargs):

import networkx as nx

g = nx.DiGraph()
g.add_edge(1,2, DIRECTIONA="oneway")
g.add_edge(1,3, DIRECTIONA="oneway")
g.add_edge(1,4, DIRECTIONA="bothDirections")
g.add_edge(2,3, DIRECTIONA="bothDirections")
g.add_edge(2,4, DIRECTIONA="oneway")


print(g.edges(data=True))
# [(1, 2, {'DIRECTIONA': 'oneway'}), (1, 3, {'DIRECTIONA': 'oneway'}), (1, 4, {'DIRECTIONA': 'bothDirections'}), (2, 3, {'DIRECTIONA': 'bothDirections'}), (2, 4, {'DIRECTIONA': 'oneway'})]

custom_reversed = nx.DiGraph()
for node_from, node_to, edge_data in list(g.edges(data=True)):  # networkx 2.4 doesn not have key parameter
    if edge_data['DIRECTIONA'] == 'bothDirections':
        custom_reversed.add_edge(node_from, node_to, **edge_data)


print(custom_reversed.edges(data=True))
[(4, 1, {'DIRECTIONA': 'bothDirections'}), (3, 2, {'DIRECTIONA': 'bothDirections'})]

推荐阅读