python - 如何添加具有现有边缘属性的边缘?
问题描述
如果它们具有特定属性,我正在尝试创建边缘的反向副本,如下所示:
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'})]
推荐阅读
- php - Laravel 以 CSV 格式下载查询结果
- google-apps-script - 仅从当前和未来日期过滤数据
- javascript - 将事件处理程序添加到引导表中的输入字段
- c# - 由于平台响应无效,无法将 Dialogflow 响应解析为 AppResponse
- angular - Angular:如何在单击不同按钮时显示具有不同内容的相同模式?
- css - 如何隐藏具有相同类的第三个元素
- javascript - javascript - 生成并打印所有学生的总平均最终成绩
- excel - 如何在excel中显示总和最大的人的名字?
- python - 使用 Python... 转到该站点,检查一个新的 zip 文件,然后
- python - 如何将此循环的结果写入文本文件?