在放射状(树状)networkx图中寻找末端节点(叶节点) [英] Find end nodes (leaf nodes) in radial (tree) networkx graph

查看:781
本文介绍了在放射状(树状)networkx图中寻找末端节点(叶节点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于下图,是否有一种简便的方法可以仅获取末端节点?

Given the following graph, is there a convenient way to get only the end nodes?

所谓末端节点,是指那些具有一个连接边缘的末端节点.我认为这些有时被称为叶节点.

By end nodes I mean those to-nodes with one connecting edge. I think these are sometimes referred to as leaf nodes.

G=nx.DiGraph()
fromnodes=[0,1,1,1,1,1,2,3,4,5,5,5,7,8,9,10]
tonodes=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]
for x,y in zip(fromnodes,tonodes):
    G.add_edge(x,y)
G.add_node(17)     # isolated node
nx.draw_shell(G)

在此示例中,它将为[6,11,12,13,14,15,16]

推荐答案

为确保定义明确:我假设您正在查找所有度数为0和度数为1的节点.计算结果.

To make sure the definition is clear: I am assuming you are looking for all nodes which have out-degree 0 and in-degree 1. This is what my calculations find.

我正在编辑原始答案,因为networkx 2.0没有nodes_iter(). 请参阅networkx 迁移指南,以了解有关转弯1的信息. x代码转换为2.0代码.

I'm editing the original answer because networkx 2.0 does not have nodes_iter(). See the networkx migration guide in general for turning 1.x code into 2.0 code.

对于networkx 2.0

如果您想要列表

[x for x in G.nodes() if G.out_degree(x)==0 and G.in_degree(x)==1]

如果您愿意使用发电机

(x for x in G.nodes() if G.out_degree(x)==0 and G.in_degree(x)==1)

这也可以在networkx 1.x中使用,但是效率较低,因为G.nodes()在1.x中创建列表.

This also works in networkx 1.x, but is less efficient because G.nodes() creates a list in 1.x.

对于网络x 1.x

如果您想要列表

[x for x in G.nodes_iter() if G.out_degree(x)==0 and G.in_degree(x)==1]

如果您愿意使用发电机

(x for x in G.nodes_iter() if G.out_degree(x)==0 and G.in_degree(x)==1)

只是一个注释-如果在使用生成器时修改G,则行为不太可能是您想要的.

and just a note - if you modify G while using the generator, the behavior is unlikely to be what you want.

这篇关于在放射状(树状)networkx图中寻找末端节点(叶节点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆