优雅地访问networkx中的边缘属性

时间:2016-02-04 00:18:25

标签: python networkx

是否确实需要访问networkx中的edge属性,下面的尴尬的第三种形式是必要的,并且前两种形式的更多svelte不会有变化吗?

import networkx as nx

G = nx.Graph()
G.add_edge(1, 2, weight=4.7 )
G.add_edge(3, 4, weight=5.8 )

# for edge in G.edges():
#     print edge['weight']
# 
# for edge in G.edges():
#     print G[edge]['weight']

for edge in G.edges():
    print G.edge[edge[0]][edge[1]]['weight']

2 个答案:

答案 0 :(得分:4)

使用data=True

import networkx as nx

G = nx.Graph()
G.add_edge(1, 2, weight=4.7)
G.add_edge(3, 4, weight=5.8)

for node1, node2, data in G.edges(data=True):
    print(data['weight'])

打印

4.7
5.8

答案 1 :(得分:1)

在NetworkX 2.4中,您也可以使用graph.edges.data()

所以在这种情况下:

import networkx as nx

G = nx.Graph()
G.add_edge(1, 2, weight=4.7)
G.add_edge(3, 4, weight=5.8)

for node1, node2, data in G.edges.data():
    print(data['weight'])

输出为

4.7
5.8