Python 使用networkx标记连接的组件
使用Python 使用networkx标记连接的组件,python,networkx,igraph,Python,Networkx,Igraph,使用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_compo
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]
,这意味着是索引为0
,1
,2
一致的节点组[0]
,[1,2,4]
,[3,5]
。如何使用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\u组件
更复杂的方法来解决我的问题从输出开始,您可以构建所需的输出格式
例如
>>> 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]
毫无疑问,
connected\u components
是我使用的networkx
最流行的方法。感谢您的示例,我将对其进行测试,并尝试使其与numpy
操作保持一致,如果可能的话。如果有人提供比连接的组件更复杂的方法,这将是一个巨大的奖励。networkx使用的算法是为每个未访问的节点执行的bfs
,该算法在节点和边的数量上是线性的。为什么你需要一个更复杂的方法?像你这样的解决方案需要一点时间,我不是networkx
的专家,所以我想知道他们是否有其他选择。顺便说一句,我使用networkx
只是为了演示,这就是为什么我在寻找类似的常见方法来解决它。