如何在Python的NetworkX中检测并统计图的重复边?
如何检测并获取图中重复边的计数?
我已通过
add_edges_from()添加了重复的图连接,比如多次添加(1,2),但打印边列表时仅被识别为1条连接。示例代码如下:test_graph = nx.Graph() test_graph.add_edges_from([(1, 2), (1, 2), (1, 3), (1, 4), (3, 4), (4, 5), (5,6), (6,7), (7,8), (6,8)]) posxx = nx.spring_layout(test_graph, scale = 1, k = 2 / np.sqrt(test_graph.order())) #planar -> no intersect nx.draw(test_graph, posxx, node_color='red', font_size = 10, node_size = 350, with_labels=True) list(test_graph.edges)当前输出为:
[(1, 2), (1, 3), (1, 4), (3, 4), (4, 5), (5, 6), (6, 7), (6, 8), (7, 8)]我希望能获取重复边的计数值,例如若添加三次(1,2),能显示该边的计数为3,请问有解决方案吗?
核心原因与解决思路
nx.Graph是简单图结构,默认不允许同一对节点之间存在多条边,重复添加的边会被自动合并。要保留并统计重复边,需要使用nx.MultiGraph(支持多重边的图类型)。
实现代码
import networkx as nx import numpy as np from collections import Counter # 替换为MultiGraph,支持多重边 test_graph = nx.MultiGraph() test_graph.add_edges_from([(1, 2), (1, 2), (1, 3), (1, 4), (3, 4), (4, 5), (5,6), (6,7), (7,8), (6,8)]) # 查看所有边(包含重复项,每条边带唯一key区分) print("所有边(含重复):") print(list(test_graph.edges(data=False, keys=True))) # 输出:[(1, 2, 0), (1, 2, 1), (1, 3, 0), (1, 4, 0), (3, 4, 0), (4, 5, 0), (5, 6, 0), (6, 7, 0), (7, 8, 0), (6, 8, 0)] # 统计每条无向边的重复次数 # 用sorted将边转为有序元组,避免(1,2)和(2,1)被误判为不同边 edge_counts = Counter(tuple(sorted(edge)) for edge in test_graph.edges(data=False)) print("\n边重复计数:") print(edge_counts) # 输出:Counter({(1, 2): 2, (1, 3): 1, (1, 4): 1, (3, 4): 1, (4, 5): 1, (5, 6): 1, (6, 7): 1, (7, 8): 1, (6, 8): 1})
额外扩展:绘图时体现边的权重
如果需要在绘图时根据重复次数调整边的粗细,可以将计数作为边的属性,再传递给绘图函数:
# 给每条边添加weight属性,值为对应计数 for edge, count in edge_counts.items(): test_graph.add_edge(edge[0], edge[1], weight=count) # 绘图时根据weight设置边宽 posxx = nx.spring_layout(test_graph, scale=1, k=2 / np.sqrt(test_graph.order())) nx.draw(test_graph, posxx, node_color='red', font_size=10, node_size=350, with_labels=True, width=[d['weight'] for u, v, d in test_graph.edges(data=True)])
内容的提问来源于stack exchange,提问作者Adi OS
相关产品推荐
相关产品推荐

