Python:避免数组上的嵌套循环

Python:避免数组上的嵌套循环,python,Python,我正在使用etree递归一个xml文件 import xml.etree.ElementTree as etree tree = etree.parse('x.xml') root = tree.getroot() for child in root[0]: for child in child.getchildren(): for child in child.getchildren(): for child in child.getchildren(

我正在使用etree递归一个xml文件

import xml.etree.ElementTree as etree
tree = etree.parse('x.xml')
root = tree.getroot()
for child in root[0]:
 for child in child.getchildren():
        for child in child.getchildren():
            for child in child.getchildren():
               print(child.attrib)
python中避免这些嵌套for循环的惯用方法是什么

  getchildren() ⇒ list of Element instances [#]
    Returns all subelements. The elements are returned in document order.

Returns:
A list of subelements.
我在网上看到了一些帖子, 但不能直接转化为我的用途


谢谢。

如果您想获取树中
n
级别的子级,然后遍历它们,您可以执行以下操作:

def childrenAtLevel(tree, n):
    if n == 1:
        for child in tree.getchildren():
            yield child
    else:
        for child in tree.getchildren():
            for e in childrenAtLevel(child, n-1):
                yield e
def getLeafNodes(tree):
    if len(tree) == 0:
         yield tree
    else:
         for child in tree.getchildren():
            for leaf in getLeafNodes(child):
                yield leaf
然后,要深入四个层次,您只需说:

for e in childrenAtLevel(root, 4):
     # do something with e
或者,如果要获取所有叶节点(即,自身没有任何子节点的节点),可以执行以下操作:

def childrenAtLevel(tree, n):
    if n == 1:
        for child in tree.getchildren():
            yield child
    else:
        for child in tree.getchildren():
            for e in childrenAtLevel(child, n-1):
                yield e
def getLeafNodes(tree):
    if len(tree) == 0:
         yield tree
    else:
         for child in tree.getchildren():
            for leaf in getLeafNodes(child):
                yield leaf

itertools.chain.from_iterable
将使一级嵌套变平;您可以使用
functools.reduce
将其应用n次():


请注意,
getchildren
已被弃用;迭代一个节点会直接产生它的子节点。

itertools.product
是避免嵌套循环的好方法。为什么这不能转化为您的使用?您是否特别想要元素4子元素的属性?对不起,我不是说itertools.product不适合我,但无法将该示例转化为数组,就像我的例子一样。我没有做太多的Python,但会尝试。