【发布时间】:2013-02-08 20:11:38
【问题描述】:
我正在使用 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.
我在 SO 中看到了一些帖子,例如, Avoiding nested for loops 但不直接转化为我的使用。
谢谢。
【问题讨论】:
-
itertools.product是避免嵌套循环的好方法。为什么这不能转化为您的使用? -
您是否特别想要 4 个子元素深度的属性?
-
抱歉,我并不是说 itertools.product 不适合我,而是无法像我的情况那样将该示例转换为数组。我没有做过很多 Python,但会尝试。
标签: python