在NetworkX图中解析边缘

12

我想从一个图中获取具有特定属性的边,但不使用get_edge_attributes()函数。我需要一种更灵活的方法来实现它。我可以获取节点属性,但由于我是新手,边似乎很难。

G = nx.read_graphml("test.graphml")

for n in G:
  print "%s\t%s" %(n, G.node[n].get(attr))

for (s,d) in G:       # and here is my problem
  print "%s->%s\t%s" %(s, d, G.edge[s][d].get(attr))
2个回答

17
您可以使用 G.edges() 或 G.edges_iter() 方法循环遍历图的所有边。
In [1]: import networkx as nx

In [2]: G = nx.Graph()

In [3]: G.add_edge(1,2,weight=7)

In [4]: G.add_edge(2,3,weight=10)

In [5]: for u,v,a in G.edges(data=True):
    print u,v,a
   ...:     
1 2 {'weight': 7}
2 3 {'weight': 10}

3

被接受的答案现在略有过时: edges_iter 方法已被弃用。

edges 属性 可以用作方法或属性。(实际上是一个可迭代和可调用的 EdgeView 值)

现在你可以通过以下方式遍历所有边:

for u,v in G.edges:
    print(u,v)

或者,像以前一样,使用数据

for u, v, d in G.edges(data=True):
    print(f"({u}, {v}) {d=}")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接