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

bsr*_*bsr 5 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():
               print(child.attrib)
Run Code Online (Sandbox Code Playgroud)

在python中避免这些嵌套for循环的惯用方法是什么.

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

Returns:
A list of subelements.
Run Code Online (Sandbox Code Playgroud)

我在SO中看到了一些帖子,比如 避免嵌套for循环 但是没有直接转换为我的使用.

谢谢.

Ord*_*Ord 3

如果你想获取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
Run Code Online (Sandbox Code Playgroud)

然后,要使元素深入四层,您只需说:

for e in childrenAtLevel(root, 4):
     # do something with e
Run Code Online (Sandbox Code Playgroud)

或者,如果您想获取所有叶节点(即本身没有任何子节点的节点),您可以执行以下操作:

def getLeafNodes(tree):
    if len(tree) == 0:
         yield tree
    else:
         for child in tree.getchildren():
            for leaf in getLeafNodes(child):
                yield leaf
Run Code Online (Sandbox Code Playgroud)