Python 从连接的组件中提取顶点的更好方法?

Python 从连接的组件中提取顶点的更好方法?,python,graph-tool,Python,Graph Tool,下图的边[(0,1),(1,2),(3,3),(3,4),(1,1),(5,5),(5,6)],应具有如下连接的组件顶点集:[0,1,2],[3,4],[5,6] 图形设置 import graph_tool as gt from graph_tool.topology import label_components edges = [(0,1),(1,2),(3,3),(3,4),(1,1),(5,5),(5,6)] g = gt.Graph() g.set_directed(False) g

下图的边
[(0,1),(1,2),(3,3),(3,4),(1,1),(5,5),(5,6)]
,应具有如下连接的组件顶点集:
[0,1,2],[3,4],[5,6]

图形设置

import graph_tool as gt
from graph_tool.topology import label_components
edges = [(0,1),(1,2),(3,3),(3,4),(1,1),(5,5),(5,6)]
g = gt.Graph()
g.set_directed(False)
g.add_edge_list(edges)
从连接的组件中提取顶点

lc = label_components(g)
[gt.GraphView(g, vfilt=lc[0].a == _).get_vertices() for _ in range(len(lc[1]))]  # [1]
输出

[array([0, 1, 2], dtype=uint64), array([3, 4], dtype=uint64), array([5, 6], dtype=uint64)]

我的问题是,这真的是最好的方法吗<代码>[1]尤其显得比必要的更复杂。可能文档中有一个函数我没有找到。

这里有一种方法,使用属性映射的
a
属性。不确定它是否比你的好得多,但它仍然是:

comp, a = gt.topology.label_components(g) 
[[i for i, x in enumerate(comp.a) if x == c] for c in range(len(a))]  
输出为:

[[0, 1, 2], [3, 4], [5, 6]]

请注意,存在一个专门通过审查改进工作代码的网站。批判性地说,在发布之前请阅读:非常感谢,但要清楚,我的问题实际上是为了在文档中找到有用的函数,而不是寻求代码改进。请注意,您并没有在问题的“图形设置”部分真正设置图形。不过,请看下面的建议解决方案。哎哟-忘了添加边缘列表谢谢你的回答-我明天早上再复习