[英]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.