gpt4 book ai didi

python - 如何返回图上的直接依赖节点

转载 作者:行者123 更新时间:2023-12-01 07:56:27 24 4
gpt4 key购买 nike

如果可能的话,我想获取给定节点的直接依赖节点。

例如,在以下示例中 nx.ancestors(G, 5) 返回 {0, 1, 2, 3, 4},这些节点是迭代依赖的在节点 5 上。但我想获取{3, 4},这些节点直接连接到节点5

此外,nx.descendants(G, 0) 返回 {1, 2, 3, 4, 5},我想在其中获取 {1 , 2} 直接连接到节点 0

import networkx as nx
import matplotlib.pyplot as plt

g = nx.Graph()
G = nx.DiGraph()

# add 5 nodes, labeled 0-4:
map(G.add_node, range(5))
# 1,2 depend on 0:
G.add_edge(0,1)
G.add_edge(0,2)
# 3 depends on 1,2
G.add_edge(1,3)
G.add_edge(2,3)
# 4 depends on 1
G.add_edge(1,4)
# 5 depends on 3 and 4
G.add_edge(3,5)
G.add_edge(4,5)

print(nx.ancestors(G, 5))
print(nx.descendants(G, 0))
<小时/>

输出:

{0, 1, 2, 3, 4}
{1, 2, 3, 4, 5}

最佳答案

您可以使用predecessorssuccessors :

set(G.predecessors(5))

输出:

{3, 4}

并且,

set(G.successors(0))

输出:

{1, 2}

关于python - 如何返回图上的直接依赖节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55953043/

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