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

标签 python networkx

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

例如,在以下示例中 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/

相关文章:

python - NetworkX:如何为现有的 G.edges() 添加权重?

python - PyCharm 找不到 Spacy 模型 'en'

python - 网格搜索CV : passing weights to a scorer

python - 对象不可订阅 networkx

Python网络X : Confining force-directed layout within circular boundary

python - 在 Python 中建立无向图模型

python - 如何使用mingw-w64,Python和pybind11手动构建C++扩展?

python - 黑色格式化程序 - 忽略特定的多行代码

python - 问题 和 列出和分隔字符

python-2.7 - python-igraph 和 networkx 之间的关系