NetworkX 最大连通分量失效?
根据networkx的文档,connected_component_subgraphs(G)会返回一个所有组件的排序列表。因此,列表中的第一个应该是最大的组件。
但是,当我尝试使用文档页面上的示例代码来获取图G的最大组件时,
G=nx.path_graph(4)
G.add_edge(5,6)
H=nx.connected_component_subgraphs(G)[0]
我得到了
TypeError: 'generator' object has no attribute '__getitem__'
在我另一台电脑上,使用早期版本的networkx(我想是1.7,不太确定)时,这个代码是可以正常工作的。
现在我在另一台电脑上使用的是python 2.7.7和networkx 1.9。这是版本的问题吗?
我自己写了一个小函数,只有几行代码,用来找出最大的组件,只是在想为什么会出现这个错误。
顺便说一下,我可以通过将生成器对象转换为列表来获取组件。
components = [comp for comp in nx.connected_components(G)]
但是这个列表并没有按照文档中所说的组件大小进行排序。
举个例子:
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
输出:
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]
看起来当节点名称是大数字,并且有很多单独的节点时,返回的子图并没有正确排序。
2 个回答
6
关于版本2.4:nx.connected_component_subgraphs(G)
这个功能被去掉了。
如果你想要得到相同的结果,可以使用:
connected_subgraphs = [G.subgraph(cc) for cc in nx.connected_components(G)]
如果你想要获取最大的那个部分,可以使用:
gcc = max(nx.connected_components(G), key=len)
giantC = G.subgraph(gcc)
19
接口已经改成返回一个生成器(你已经发现了这一点)。文档中的例子展示了如何实现你想要的功能。
生成一个按大小排序的连通分量列表,最大的在前面。
>> 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]]
或者
>>> sorted(nx.connected_component_subgraphs(G), key = len, reverse=True)