如何解决Python & NetworkX - 如何检查节点是否自循环
我有一个像这样有 2 个 ID 字段的表,其中父级可以链接到自身:
孩子 | 父母 |
---|---|
1 | 1 |
2 | 1 |
3 | 1 |
4 | 2 |
5 | 3 |
我使用 networkx 创建了一个有向图,现在正在尝试编写一个函数来识别每一行的所有根和叶,并将它们添加回原始数据帧:
def find_leaves(G,node):
d = list(nx.descendants(G,node))+[node]
H = G.subgraph(d)
return [a for a in H.nodes if H.out_degree(a)==0 | (H.out_degree(a)==1 and <checking whether the node is a self-loop>)]
def find_roots(G,node):
d = list(nx.ancestors(G,node))+[node]
H = G.subgraph(d)
return [a for a in H.nodes if H.in_degree(a)==0 | (H.in_degree(a)==1 and <checking whether the node is a self-loop>)]
因为父/子可以链接到自身,我希望添加第二个子句来检查出/入度是否 = 1 并且节点是否是自循环。我对 networkx 相当陌生,但从 2.5 文档看来,自循环的大多数函数都返回图中的整个自循环节点列表,例如nx.nodes_with_selfloops(G).
有没有办法检查一个节点是否自循环,而不必每次都检查整个列表?
解决方法
是的。以节点为键将有向图作为字典访问将返回一个 AtlasView,它给出了该节点的所有边。例如
>>> g[2]
AtlasView({1: {}})
因此,要查找节点是否具有连接回自身的边,您只需检查该节点是否存在于该视图中。
def is_self_looped(g,node):
return node in g[node]
在您的示例中,只有 1 个具有自循环。
>>> for node in g.nodes:
... print(node,is_self_looped(g,node))
...
1 True
2 False
3 False
4 False
5 False
,
this.items = [];
输出:
def has_self_loop(G: nx.Graph,node):
try:
if G[node][node] != None:
return True
except Exception:
return False
G_edges = [(1,1),(2,3),(3,3)]
G = nx.Graph()
G.add_edges_from(G_edges)
[print(node,"has self loop") for node in G.nodes() if has_self_loop(G,node) == True]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。