NetworkX最大的组件不再工作?

sop*_*adw 11 python networkx

根据networkx文档,connected_component_subgraphs(G)返回所有组件的排序列表.因此,第一个应该是最大的组件.

但是,当我尝试使用文档页面上的示例代码获取图G的最大组件时

G=nx.path_graph(4)
G.add_edge(5,6)
H=nx.connected_component_subgraphs(G)[0]
Run Code Online (Sandbox Code Playgroud)

我明白了

TypeError: 'generator' object has no attribute '__getitem__'
Run Code Online (Sandbox Code Playgroud)

它曾经在我的另一台计算机上运行早期版本的networkx(1.7我想,不是100%肯定)

现在我使用的是另一台配备python 2.7.7和networkx 1.9的计算机.这是版本问题吗?

我自己编写了一个带有几行的小函数来找到最大的组件,只是想知道为什么会出现这个错误.

顺便说一句,我可以通过将生成器对象转换为列表来获取组件.

components = [comp for comp in nx.connected_components(G)]
Run Code Online (Sandbox Code Playgroud)

但是列表不按文档中所述的组件大小排序.

例:

G = nx.Graph()
G.add_edges_from([(1,2),(1,3),(4,5)])
G.add_nodes_from(range(6,20))
components = [comp for comp in nx.connected_components(G)]
component_size = [len(comp) for comp in components]
print G.number_of_nodes(), G.number_of_edges(), component_size

G = nx.Graph()
G.add_edges_from([(1000,2000),(1000,3000),(4000,5000)])
G.add_nodes_from(range(6,20))
components = [comp for comp in nx.connected_components(G)]
component_size = [len(comp) for comp in components]
print G.number_of_nodes(), G.number_of_edges(), component_size
Run Code Online (Sandbox Code Playgroud)

输出:

19 3 [3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
19 3 [2, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Run Code Online (Sandbox Code Playgroud)

看起来当节点名称是大数字时,并且当存在一堆单个节点时,返回的子图不能正确排序

Ari*_*ric 16

networkx-1.9文档在http://networkx.github.io/documentation/networkx-1.9/reference/generated/networkx.algorithms.components.connected.connected_components.html#networkx.algorithms.components.connected.connected_components

接口已更改为返回生成器(如您所知).文档中的示例显示了如何执行您的要求.

生成已连接组件的排序列表,最大值.

>> G = nx.path_graph(4)
>>> G.add_path([10, 11, 12])
>>> sorted(nx.connected_components(G), key = len, reverse=True)
[[0, 1, 2, 3], [10, 11, 12]]
Run Code Online (Sandbox Code Playgroud)

要么

>>> sorted(nx.connected_component_subgraphs(G), key = len, reverse=True)
Run Code Online (Sandbox Code Playgroud)


wil*_*ack 6

至于2.4版本: nx.connected_component_subgraphs(G)被删除。

相反,要获得相同的结果,请使用:

connected_subgraphs = [G.subgraph(cc) for cc in nx.connected_components(G)]
Run Code Online (Sandbox Code Playgroud)

并获得巨大的组件:

gcc = max(nx.connected_components(G), key=len)
giantC = G.subgraph(gcc)
Run Code Online (Sandbox Code Playgroud)