首页 > 解决方案 > 如何获得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?

标签: python-3.xgraphnetworkx

解决方案


对于一个边缘:

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

推荐阅读