Sunday, 15 January 2012

Python: avoid nested loop on array -



Python: avoid nested loop on array -

i recursing through xml file, using etree.

import xml.etree.elementtree etree tree = etree.parse('x.xml') root = tree.getroot() kid in root[0]: kid in child.getchildren(): kid in child.getchildren(): kid in child.getchildren(): print(child.attrib)

what idiomatic way in python avoid these nested loop.

getchildren() ⇒ list of element instances [#] returns subelements. elements returned in document order. returns: list of subelements.

i saw post in like, avoiding nested loops doesn't straight translate use.

thanks.

if want children n levels deep in tree, , iterate through them, can do:

def childrenatlevel(tree, n): if n == 1: kid in tree.getchildren(): yield kid else: kid in tree.getchildren(): e in childrenatlevel(child, n-1): yield e

then, elements 4 levels deep, say:

for e in childrenatlevel(root, 4): # e

or, if want of leaf nodes (i.e. nodes don't have children themselves), can do:

def getleafnodes(tree): if len(tree) == 0: yield tree else: kid in tree.getchildren(): leaf in getleafnodes(child): yield leaf

python

No comments:

Post a Comment