Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用networkx标记连接的组件_Python_Networkx_Igraph - Fatal编程技术网

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
只是为了演示,这就是为什么我在寻找类似
的常见方法来解决它。