我有一本带有节点的字典:
supernodes = list(nx.connected_components(G1))
的结果print(supernodes) is:
print(supernodes)
[{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 个合约节点?
nx.contracted_nodes(G, (1, 3))
{1,2,3,5}, {8,6}
你可以试试这个:
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).
G1
nx.contracted_nodes(G1, nodes[0], node, self_loops=False)