Python: avoid nested loop in array

I recurse through an XML file using etree.

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)

what is the idiomatic way in python to avoid this nested loop.

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

Returns:
A list of subelements.

I saw a message in SO, like, Preventing nested loops but it doesn't directly translate into my use.

thank.

+5
source share
2 answers

If you want children who are nlevels deep in the tree and then iterate over them, you can do:

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

Then, to get the elements at four levels in depth, you simply say:

for e in childrenAtLevel(root, 4):
     # do something with e

Or, if you want to get all leaf nodes (i.e. nodes that themselves do not have any children), you can do:

def getLeafNodes(tree):
    if len(tree) == 0:
         yield tree
    else:
         for child in tree.getchildren():
            for leaf in getLeafNodes(child):
                yield leaf
+3
source

itertools.chain.from_iterable ; functools.reduce, n ( "n" -time- ):

from itertools import chain
from functools import reduce

for child in reduce(lambda x, _: chain.from_iterable(x), range(3), root):
    print(child.attrib)

, getchildren ; node .

+2

All Articles