开发者

How to make a double 'continue' in a loop?

Is it poss开发者_StackOverflowible to make a double continue and jump to the item after the next item in the list in python?


Not really, but you can use a variable telling it to continue again after the first continue:

continue_again = False
for thing in things:
    if continue_again:
        continue_again = False
        continue
    # ...
    if some_condition:
        # ...
        continue_again = True
        continue
    # ...


Use an iterator:

>>> 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

Using the next builtin with a default of None avoids raising StopIteration -- thanks kevpie for the suggestion!


Can you just increment the iterator?

for i in range(len(list)):
    i = i + 1
    continue
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜