本文介绍了在Python ElementTree中,如何获取树中某个元素的所有祖先的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要 get_ancestors_recursively功能。

示例运行可以是

I need "get_ancestors_recursively" function.
A sample run can be

>>> dump(tr)
<anc1>
  <anc2>
    <element> </element>
  </anc2>
</anc1>
>>> input_element = tr.getiterator("element")[0]
>>> get_ancestors_recursively(input_element)
['anc1', 'anc2']

有人可以帮我吗

推荐答案

在最新版本的ElementTree(v1.3或更高版本)中,您只需执行

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

input_element.find('..')

递归地。但是,Python附带的ElementTree没有此功能,并且我在Element类中看不到任何东西。

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

由于DFS,这很慢,并且可以列出很多垃圾收集列表,但是如果可以的话,应该没问题

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.

这篇关于在Python ElementTree中,如何获取树中某个元素的所有祖先的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:24