开发者

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

开发者 https://www.devze.com 2023-02-28 16:58 出处:网络
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 th

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

精彩评论

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