问题描述
我使用 networkx
从节点列表创建了一个图表.它有自循环.如何删除它们?以下是示例:
I have created a graph from list of nodes using networkx
. It has self loops. How to remove them? Following is sample:
import networkx as NX
G=NX.Graph()
G.add_edge(1,2)
G.add_edge(1,1)
print (G.edges())
[(1, 2), (1, 1)]
我不想要 (1, 1)
边.
推荐答案
(以下针对 networkx 1.x 的说明)
(instructions for networkx 1.x below)
如果您使用的是 networkx 2.x,请尝试
If you're using networkx 2.x try
G.remove_edges_from(nx.selfloop_edges(G))
如果您有一个 MultiGraph
(例如 configuration_model
生成),如果您有一个带有小错误的旧版本 2.x,这可能不起作用.如果是这样并且您不想升级,那么您需要在删除边缘之前将其转换为列表.
If you have a MultiGraph
(which for example configuration_model
produces), this may not work if you have an older release of 2.x with a minor bug. If so and you don't want to upgrade, then you need to convert this into a list before removing edges.
G.remove_edges_from(list(nx.selfloop_edges(G)))
此错误已更正 https://github.com/networkx/networkx/issues/4068.
在版本 1.x(当我最初回答这个问题时)是:
In version 1.x (when I originally answered this question), it was:
G.remove_edges_from(G.selfloop_edges())
这篇关于从无向网络x图中去除自环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!