[Python] Better way to extract vertices from connected components?

Discussão em 'Python' iniciado por Stack, Agosto 1, 2025.

  1. Stack

    Stack Membro Participativo

    The following graph, with edges [(0,1),(1,2),(3,3),(3,4),(1,1),(5,5),(5,6)], should have connected component vertex sets as follow: [0, 1, 2], [3, 4], [5, 6].

    graph setup

    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)


    extract vertices from connected components

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


    output

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


    My question is, is this really the best approach? [1] in particular seems more convoluted than might be necessary. Maybe there's a function in the documentation that I'm not finding.

    Continue reading...

Compartilhe esta Página