网络x

时间:2019-05-30 14:18:35

标签: python graph networkx topology

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

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)时合并边。在我的示例中,我需要删除节点128,并连接3-66-9。因此,我希望结果如下。 enter image description here

我该怎么办?十分感谢

1 个答案:

答案 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)

enter image description here