如何在NetworkX中收缩只有2个边的节点?

3

我有一个在 NetworkX 中的图,大致长这样:

a---b---c---d
    |
    e---f

我希望您能够简化它,删除仅有2条边的中间节点。
a---b---d
    |
    f

这可以在NetworkX中如何完成?我只看到删除节点方法或合并边缘。但这与节点有关。

1
请查看:https://stackoverflow.com/a/54060830/3782865 - zohar.kom
2个回答

3
可以按照以下步骤完成:
for node in list(G.nodes()):
    if G.degree(node) == 2:
        edges = list(G.edges(node))
        G.add_edge(edges[0][1], edges[1][1])
        G.remove_node(node)

0

更简洁的@zohar.kom版本将使用子图方法:

import networkx as nx
import matplotlib.pyplot as plt

graph = nx.random_graphs.watts_strogatz_graph(100, 3, .4)

threshold = 2
sub       = graph.subgraph([node for node in graph.nodes() if \
                            graph.degree(node) != threshold])

fig, ax = plt.subplots(2, 1)

nx.draw(graph, ax = ax[0], with_labels = 1)
nx.draw(sub, ax = ax[1], with_labels = 1)

enter image description here


1
  1. 我假设你的意思是[node for node in graph.nodes() if graph.degree(node) != threshold],否则我们只会得到要删除的节点,而不是我们实际想要的节点。
  2. 这还不够,因为你只删除了相关的节点,这很好,但你还需要添加边。例如,在原始示例中,边(b,f)将在此实现中丢失。
- zohar.kom
1
啊,我没有仔细阅读它。你是对的,这种方法有点无意义。感谢你指出来。 - cvanelteren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接