根据 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]
看起来当节点名称是大数字,且存在许多单个节点时,返回的子图未能正确排序
list
,例如list(nx.connected_components(G))
。 如果您只想要生成器产生的第一个元素,则可以使用next
,例如next(nx.connected_components(G))
。 - DSMnx.connected_component_subgraphs(G)[0]
时,你是否收到错误消息? - sophiadw