我使用etree通过xml文件递归。Python:避免在数组上嵌套循环
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.
我看到一些帖子在这么喜欢, Avoiding nested for loops 但并不直接转化为我所用。
谢谢。
'itertools.product'是避免嵌套循环的好方法。为什么不能转化为您的使用? – 2013-02-08 20:13:29
您是否特意要素4孩子的属性? – bogatron 2013-02-08 20:15:36
抱歉,我并不是说itertools.product不适合我,但无法将该示例转换为像我这样的数组。我没有做太多的Python,但会尝试。 – bsr 2013-02-08 20:30:21