gpt4 book ai didi

python - 删除入度和出度都等于 1 的 networkx DiGraph 中的所有节点

转载 作者:太空狗 更新时间:2023-10-30 00:41:09 26 4
gpt4 key购买 nike

假设我在 NetworkX 中制作有向图:

import networkx as nx

G = nx.DiGraph()

n = ["A","B","C","D","E","F","H","I","J","K","L","X","Y","Z"]

e = [("A","Z"),("Z","B"),("B","Y"),("Y","C"),("C","G"),("G","H"),("G","I"),("I","J"),("K","J"),("J","L"),("F","E"),("E","D"),("D","X"),("X","C")]

G.add_nodes_from(n)

G.add_edges_from(e)

我如何删除所有入度和出度都等于 1 的节点,以便我的图看起来像这样?:

import networkx as nx

G = nx.DiGraph()

n = ["A","C","F","G","H","J","K","L"]

e = [("A","C"),("C","G"),("G","H"),("G","J"),("K","J"),("J","L")

G.add_nodes_from(n)

G.add_edges_from(e)

想法是移除“流通”节点并保留连接性。

最佳答案

尽管我看不到最终结果中从 ("A", "C") 和 ("G", "J") 获得边缘的位置,但以下代码可以满足您的需求。

import networkx as nx

def remove_edges(g, in_degree=1, out_degree=1):
g2=g.copy()
d_in=g2.in_degree(g2)
d_out=g2.out_degree(g2)
print(d_in)
print(d_out)
for n in g2.nodes():
if d_in[n]==in_degree and d_out[n] == out_degree:
g2.remove_node(n)
return g2

G_trimmed = remove_edges(G)
G_trimmed.edges()
#outputs [('C', 'G'), ('G', 'H'), ('K', 'J'), ('J', 'L')]
G_trimmed.nodes()
#outputs ['A', 'C', 'G', 'F', 'H', 'K', 'J', 'L']

关于python - 删除入度和出度都等于 1 的 networkx DiGraph 中的所有节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17735252/

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