收缩networkx中的节点列表

2024-04-05

我有一本带有节点的字典:

supernodes = list(nx.connected_components(G1))

的结果print(supernodes) is:

[{1, 2, 3, 5}, {8, 6}, {7, 9, 10, 12, 13}, {4}, {11}, {14}, {15}]

如何将每个列表合并到一个节点?我发现了这个功能nx.contracted_nodes(G, (1, 3))但我怎样才能把{1,2,3,5}, {8,6}等等并创建 7 个合约节点?


你可以试试这个:

import networkx as nx
# Preamble, define G1 

# contract nodes
for supernode in nx.connected_components(G1):
    nodes = sorted(list(supernode))
    for node in nodes[1:]:
        G1 = nx.contracted_nodes(G1, nodes[0], node)

每个节点x在G1对应于具有 x 作为较小元素的超级节点。如果你想删除自循环,请改为编写nx.contracted_nodes(G1, nodes[0], node, self_loops=False).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

收缩networkx中的节点列表 的相关文章

随机推荐