我有一个无向图,如下所示:
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()
我想在节点满足degree=n(like 2)
时合并边。在我的示例中,我需要删除节点1
,2
和8
,并连接3-6
和6-9
。因此,我希望结果如下。
我该怎么办?十分感谢
答案 0 :(得分:1)
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)