如何添加具有现有边属性的边?
How to add an edge with the attributes of an already existing edge?
如果边缘具有如下特定属性,我将尝试创建边缘的反转副本:
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' 下的另一个字典中。有没有什么办法可以简单地拥有属性字典而不是在另一个字典中?由于格式不同,它使已经编写的代码无法运行,谢谢。
您需要将边缘属性作为多个关键字参数提供(通常在函数签名中表示为 **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'})]
如果边缘具有如下特定属性,我将尝试创建边缘的反转副本:
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' 下的另一个字典中。有没有什么办法可以简单地拥有属性字典而不是在另一个字典中?由于格式不同,它使已经编写的代码无法运行,谢谢。
您需要将边缘属性作为多个关键字参数提供(通常在函数签名中表示为 **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'})]