gpt4 book ai didi

python - 当网络x中节点度数为n时合并边

转载 作者:行者123 更新时间:2023-12-01 00:53:46 24 4
gpt4 key购买 nike

我有一个无向图,如下所示:

import networkx as nx
import matplotlib.pyplot as plt

l = [('1','2'),('2','3'),('3','4'),('3','5'),('1','6'),('6','7'),('6','8'),('9','8')]

G=nx.Graph()
G.add_edges_from(l)
nx.draw_networkx(G,with_labels=True)
plt.show()

enter image description here

当节点满足 degree=n(like 2) 时,我想合并边。我需要删除节点 1 , 28 ,并连接 3-66-9在我的例子中。所以我预计结果如下。 enter image description here

我该怎么做?提前致谢

最佳答案

import networkx as nx
import matplotlib.pyplot as plt

l = [('1','2'),('2','3'),('3','4'),('3','5'),('1','6'),('6','7'),('6','8'),('9','8')]

G=nx.Graph()
G.add_edges_from(l)

# Select all nodes with only 2 neighbors
nodes_to_remove = [n for n in G.nodes if len(list(G.neighbors(n))) == 2]

# For each of those nodes
for node in nodes_to_remove:
# We add an edge between neighbors (len == 2 so it is correct)
G.add_edge(*G.neighbors(node))
# And delete the node
G.remove_node(node)

nx.draw(G,with_labels=True)

enter image description here

关于python - 当网络x中节点度数为n时合并边,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56380053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com