python - 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 语句中使用新的“元素”变量。因此,我希望下一个循环迭代循环遍历“新”元素的每个子节点,而不是从第一次迭代开始的那个
有什么办法可以做到这一点吗?
解决方案
我想这就是你要找的:
sequence = iter(xmlDoc.find("...").getchildren())
while True:
try:
element = next(sequence)
except StopIteration:
break
# handle element ...
if some_condition:
sequence = iter(xmlDoc.find("...").getchildren())
推荐阅读
- javascript - 将 axios 请求传递给 vue.js 中的子组件
- python - Django REST FileUpload Parser 不适用于图像
- css - LESS CSS 条件不评估 iscolor
- apache-spark - 使用 pyspark 中的 groupBy 函数使用 QuantileDiscretizer 进行分桶
- c++ - “未定义引用”Ros Cpp 库问题
- python - 使用 Django 和数据库代码的连接中止错误
- python - 使用 Fastai 的并行函数进行 pandas 聚合
- python - 为 3 维向量创建一个类
- python - 循环遍历一个txt文件
- sql-server - 在查询期间动态调整事务隔离级别