首页 > 解决方案 > for 循环中的变量将成为外部循环 Python 的新迭代器

问题描述

假设我有以下示例代码:

element = xmlDoc.find("...") # this returns an element that is found within an XML document
for child in element.getchildren():
    # iterate over each child
    # do some stuff
    if some_condition: # assume that at some point in the loop, this condition is executed
        element = xmlDoc.find("..." # find a new element in the doc and this element should be the new element to iterate over from the next loop

在这一点上,这显然是非常理论化的。我想要做的是通过查看某个“元素”节点的每个子节点来开始一个循环。但是,如果 some_condition 被执行(它将在我的代码中的某个点执行),那么我希望下一个 for 循环迭代在该 if 语句中使用新的“元素”变量。因此,我希望下一个循环迭代循环遍历“新”元素的每个子节点,而不是从第一次迭代开始的那个

有什么办法可以做到这一点吗?

标签: pythonxmllxml

解决方案


我想这就是你要找的:

sequence = iter(xmlDoc.find("...").getchildren())
while True:
    try:
        element = next(sequence)
    except StopIteration:
        break
    # handle element ...
    if some_condition:
        sequence = iter(xmlDoc.find("...").getchildren())

推荐阅读