如何在循环中实现双重'继续'?
在Python中,能不能实现一个双重跳过的功能,也就是跳过当前项和下一个项,直接到列表中的下下个项呢?
3 个回答
-2
你能直接让这个迭代器加一吗?
for i in range(len(list)):
i = i + 1
continue
10
其实不是这样,但你可以用一个变量来告诉它在第一次继续之后再继续
。
continue_again = False
for thing in things:
if continue_again:
continue_again = False
continue
# ...
if some_condition:
# ...
continue_again = True
continue
# ...
10
使用迭代器:
>>> list_iter = iter([1, 2, 3, 4, 5])
>>> for i in list_iter:
... print "not skipped: ", i
... if i == 3:
... print "skipped: ", next(list_iter, None)
... continue
...
not skipped: 1
not skipped: 2
not skipped: 3
skipped: 4
not skipped: 5
用内置的 next
函数,并设置默认值为 None
,这样就不会出现 StopIteration
的错误了——感谢 kevpie 的建议!