首页 > 解决方案 > networkx 边缘返回错误的索引

问题描述

我从几天开始使用 python 和 networkx。我有一个无向图,我尝试迭代节点的边缘。

我用了

print (G.edges)

for i in G.nodes:

    print( G.edges(i))

获得

[(0, 1), (0, 2), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

[(0, 1), (0, 2), (0, 4)]

[(1, 0), (1, 2), (1, 3), (1, 4)]

[(2, 0), (2, 1), (2, 3), (2, 4)]

[(3, 1), (3, 2), (3, 4)]

[(4, 0), (4, 1), (4, 2), (4, 3)]

提供的边G.edges()在某些情况下使两个节点颠倒(例如,对于 i=1,我有边 (1,0),但它不存在!!我只有 (0,1)。由于图形是无向的,它是相同的边缘,但是如果我尝试将其用作边缘向量的索引,则它不起作用。

我试过了

for i in G. nodes
...   do something with .... x[e] for e in G.edges(i)

标签: pythonnetworkxgraph-theory

解决方案


您可以将列表扩展为G.edges()双向

a = [e for e in G.edges]

[(0, 1), (0, 2), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]根据networkx Documentation ,为您提供了删除无向边的重复表示的边列表,而跨所有节点的邻居报告自然会报告两个方向。

您可以:

1)通过以相反的顺序添加边表示来复制列表

a = [e for e in G.edges] + [(y, x) for (x, y) in G.edges]

这给了你

[(0, 1), (0, 2), (0, 4), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4), (1, 0), (2, 0), (4, 0), (2, 1), (3, 1), (4, 1), (3, 2), (4, 2), (4, 3)]

或者; 2)使用列表理解从G.edges(i)像你一样获得优势:

b = [e for i in G.nodes for e in G.edges(i)]

输出:

[(0, 1), (0, 2), (0, 4), (1, 0), (1, 2), (1, 3), (1, 4), (2, 0), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 0), (4, 1), (4, 2), (4, 3)]

推荐阅读