需要从python列表中查找子元素 [英] need to find child element from python list

查看:84
本文介绍了需要从python列表中查找子元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下的python列表

i have a python list as below

[(u'1', u'0'), (u'2', u'1'), (u'3', u'2'), (u'4', u'3'), (u'5', u'4'), (u'6', u'4'), (u'7', u'4'), (u'8', u'4'), (u'9', u'4'), (u'10', u'4'), (u'11', u'4'), (u'11.5', u'2'), (u'12', u'11.5'), (u'13', u'11.5'), (u'14', u'11.5'), (u'15', u'11.5'), (u'16', u'11.5'), (u'17', u'11.5'), (u'18', u'11.5'), (u'19', u'11.5'), (u'20', u'11.5'), (u'21', u'11.5'), (u'22', u'11.5'), (u'23', u'11.5'), (u'24', u'11.5'), (u'25', u'11.5'), (u'26', u'11.5'), (u'27', u'11.5'), (u'28', u'11.5'), (u'30', u'11.5'), (u'29', u'11.5')]

这里每个元组的第一个位置是它自己的id,而第二个位置是它的父母身份。

here each tuple's 1st place is its own id while 2nd position is its parent id.

我希望得到所有特定身份的孩子。
例如,如果我想获得自己的id为3的孩子(或孩子的孩子......到n深度)的所有自己的列表。
所以答案列表将是 [u'4',u'5',u'6',u'7',u'8',u'9',u'10' ,u'11']

i want to get all child of specific id. Example, if i want to get the list of all ownids who are child(or child of child... to n depth) of own id "3". so answer list will be [u'4', u'5', u'6', u'7', u'8', u'9', u'10', u'11']

以任何方式做到这一点?

any way to do this??

推荐答案

您可以使用 networkx 库...

import networkx as nx
g = nx.DiGraph()
g.add_edges_from( (y,x) for x,y in your_list )
print list(nx.dfs_postorder_nodes(g, '3'))
[u'11', u'10', u'5', u'7', u'6', u'9', u'8', u'4', '3']

这篇关于需要从python列表中查找子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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