python elementtree 父节点_在Python ElementTree中,如何获取树中某个元素的所有祖先的列表?...

在Python的ElementTree库中,如果想要获取树中某个元素的所有祖先,由于标准库的限制,需要自定义函数实现。本文提供了一个名为`get_ancestors_recursively`的递归函数,通过深度优先搜索遍历元素树来找到祖先节点。
摘要由CSDN通过智能技术生成

I need "get_ancestors_recursively" function.

A sample run can be

>>> dump(tr)

>>> input_element = tr.getiterator("element")[0]

>>> get_ancestors_recursively(input_element)

['anc1', 'anc2']

Can somebody help me with this ?

解决方案

In the latest version of ElementTree (v1.3 or later), you can simply do

input_element.find('..')

recursively. However, the ElementTree that ships with Python doesn't have this functionality, and I don't see anything in the Element class that looks upwards.

I believe this means you have to do it the hard way: via an exhaustive search of the element tree.

def get_ancestors_recursively(e, b):

"Finds ancestors of b in the element tree e."

return _get_ancestors_recursively(e.getroot(), b, [])

def _get_ancestors_recursively(s, b, acc):

"Recursive variant. acc is the built-up list of ancestors so far."

if s == b:

return acc

else:

for child in s.getchildren():

newacc = acc[:]

newacc.append(s)

res = _get_ancestors_recursively(child, b, newacc)

if res is not None:

return res

return None

This is slow because of the DFS, and cranks out a lot of lists for garbage collection, but if you can deal with that it should be fine.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值