簡體   English   中英

使用 networkx 標記連接的組件

[英]tagging connected components using networkx

使用igraph我可以為每個節點分配連接組件的唯一 ID:

import igraph 
def tag_components(vertices, edges):
    graph = igraph.Graph()
    graph.add_vertices(vertices)
    graph.add_edges(edges)
    graph_tags = graph.clusters().membership
    return graph_tags
print(tag_components([0,1,2,3,4,5], [[1,2],[2,4],[3,5]]))

它輸出[0, 1, 1, 2, 1, 2]這意味着是 3 個連接組件索引為0 , 1 , 2節點組[0] , [1, 2, 4] , [3, 5] 如何使用networkx?實現相同的輸出networkx?

我期待這樣的事情:

def tag_components_nx(vertices, edges):
    G = nx.Graph()
    G.add_nodes_from(vertices)
    G.add_edges_from(edges)
    ...
    return graph_tags

更新

我已經有了一個滿意的答案,我想知道networkx是否有比connected_components適合我的問題的復雜方法

nx.connected_components的輸出開始,您可以構建所需的輸出格式。

例子。

>>> g.nodes()
NodeView((0, 1, 2, 3, 4, 5))
>>> g.edges()
EdgeView([(1, 2), (2, 4), (3, 5)])
>>> idx_components = {u:i for i,node_set in enumerate(nx.connected_components(g)) for u in node_set}
>>> res = [idx_components[u] for u in vertices]
>>> res
[0, 1, 1, 2, 1, 2]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM