【发布时间】:2016-10-17 07:55:42
【问题描述】:
我有以下代码:
for i in list1:
if i == 5:
#skip the NEXT iteration (not the end of this one)
else:
#do something
如何跳过引发跳过的迭代之后的迭代。比如list1=[1, 2, 3, 4, 5, 6, 7],循环会跳过6,直接跳到7,因为5触发了跳过
我见过this 问题和其他几个问题,但它们都处理跳过当前 迭代,而我想跳过下一个 迭代。这些问题的答案建议continue,据我所知,这将停止当前迭代的其余部分并继续进行下一个迭代,这不是我想要的。如何在循环中跳过单个迭代?
编辑:有人建议使用next(),但这对我不起作用。当我运行以下代码时:
a = [1, 2, 3, 4, 5, 6, 7, 8]
ai = iter(a)
for i in a:
print i
if i == 5:
_ = next(ai)
我明白了
1
2
3
4
5
6 #this should not be here
7
8
使用next()也是本题的建议:Skip multiple iterations in loop python
【问题讨论】:
-
这是你的错误:
for i in a:。应该是for i in ai: