I have the following code:
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触发了跳过。我看过这个问题和其他几个问题,但它们都处理跳过当前迭代,而我想跳过下一个迭代。那些问题的答案建议使用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)
I get
1
2
3
4
5
6 #this should not be here
7
8
在这个问题中,使用next()
也是建议: 跳过循环中多个迭代的Python
for i in a:
。应该是for i in ai:
。 - Moses Koledoye