python-3.x - 如何获得networkx中无向边的权重?
问题描述
import networkx as nx
G=nx.Graph()
connections = [(0, 1, 4), (0, 7, 8), (1, 7, 11),(1, 2, 8), (2, 8, 2), (7, 8, 7),
(7, 6, 1), (8, 6, 6), (2, 5, 4), (6, 5, 2), (2, 3, 7), (3, 5, 14),
(3, 4, 9), (5, 4, 10), ]
G.add_weighted_edges_from(connections)
在这段代码中,我怎样才能得到两个节点之间的权重?(即)5和4?
解决方案
对于一个边缘:
G.edges[5,4]['weight']
> 4
对于一个节点的所有边:
G.edges(5, data=True)
> EdgeDataView([(5, 2, {'weight': 4}), (5, 6, {'weight': 2}), (5, 3, {'weight': 14}), (5, 4, {'weight': 10})])
对于所有边:
for u, v, w in G.edges(data=True):
print(u, v, w['weight'])
> 0 1 4
> 0 7 8
> 1 7 11
> 1 2 8
> 7 8 7
> 7 6 1
> 2 8 2
> 2 5 4
> 2 3 7
> 8 6 6
> 6 5 2
> 5 3 14
> 5 4 10
> 3 4 9
推荐阅读
- node.js - 如何从同一个节点 CLI 动态导入 commonJS 和 ES6 模块?
- scheme - 如何在 scm 方案中定义一个函数来测试其参数是否为宏?
- reactjs - 如何访问异步函数中的 React.useState 值?
- javascript - 如何防止在 addEventListener 中重复执行函数?
- python - 在熊猫中使用正则表达式修改特定字符之前的列数据
- javascript - 如何在命令中向通道发送消息?
- awk - awk 不能同时使用 FIELDWIDTHS 和 OFS
- c - 在c中执行字符串的内容
- azure - 在 Azure devops 中使用“Workspace Clean”时的问题
- cordova - 如何在 Oculus Quest 上调试我的 Cordova 应用程序?