繁体   English   中英

networkx 边缘返回错误的索引

[英]networkx edges return wrong indices

我从几天开始使用 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)

您可以将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)]

output:

[(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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM