python - 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)
解决方案
您可以将列表扩展为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)]
推荐阅读
- c - 使用 openmp 并行化矩阵以避免错误共享
- python - 在 Django 的 collectstatic 中自定义忽略模式列表的示例
- r - 如何使用 Geom_bar 和 Facet_grid 设置一致的标签
- android - 如何正确暂停 AudioTrack 并恢复流畅播放?
- oracle - 如何使用 ODI-SDK 进行逆向工程?
- php - 几乎不知道为什么我们在 Laravel 中使用 Request::is() 和 @can
- kubernetes - 回忆其他清单中的 Kubernetes 注释
- oauth - Azure 中的消费层和基本层中的 OAuth
- postgresql - 使用 Go 从关系数据库中存储/检索大量数字
- javascript - jQuery div empty 后无法在 div 框中再次添加数据?