for循环内的变量成为外循环的新迭代器Python
Variable within for loop to be new iterator for outer loop 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
在这一点上,这显然是非常理论化的。我想要做的是通过查看某个 "element" 节点的每个子节点来开始循环。但是,如果 some_condition 被执行(这将在我的代码中的某个时刻执行),那么我希望下一个 for 循环迭代在该 if 语句中使用新的 "element" 变量。因此,我希望下一个循环迭代遍历 "new" 元素的每个子节点,而不是从第一次迭代开始的子节点
有什么方法可以做到这一点吗?
我想这就是您要找的:
sequence = iter(xmlDoc.find("...").getchildren())
while True:
try:
element = next(sequence)
except StopIteration:
break
# handle element ...
if some_condition:
sequence = iter(xmlDoc.find("...").getchildren())
假设我有以下示例代码:
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
在这一点上,这显然是非常理论化的。我想要做的是通过查看某个 "element" 节点的每个子节点来开始循环。但是,如果 some_condition 被执行(这将在我的代码中的某个时刻执行),那么我希望下一个 for 循环迭代在该 if 语句中使用新的 "element" 变量。因此,我希望下一个循环迭代遍历 "new" 元素的每个子节点,而不是从第一次迭代开始的子节点
有什么方法可以做到这一点吗?
我想这就是您要找的:
sequence = iter(xmlDoc.find("...").getchildren())
while True:
try:
element = next(sequence)
except StopIteration:
break
# handle element ...
if some_condition:
sequence = iter(xmlDoc.find("...").getchildren())