如何获得NetworkX图的巨大组件?

时间:2014-09-29 17:45:31

标签: python networkx

我不知道NetworkX最近是否将其中一种方法调整为生成器而不是返回列表,但我正在寻找一种好的(相当好的)方法来获取GC的GC曲线图。

我有一个工作但非常低效的代码片段:

# G = nx.Graph()
giant = sorted(nx.connected_component_subgraphs(G), key=len, reverse=True)[0]

有更清洁的方式吗?

2 个答案:

答案 0 :(得分:14)

在networkx 1.9中,connected_components_subgraphs返回迭代器(而不是排序列表)。迭代器产生的值是not in sorted order。因此,要找到最大的,请使用max

giant = max(nx.connected_component_subgraphs(G), key=len)

排序为O(n log n)。取最大值是O(n)。

答案 1 :(得分:6)

在networkx 2.4中,nx.connected_component_subgraphs()已过时,因此以下方法应该起作用:

Gcc = sorted(nx.connected_components(G), key=len, reverse=True)
G0 = G.subgraph(Gcc[0])

G0是巨大的组成部分。