How do I skip a few iterations in a for loop

后端 未结 4 1977
我寻月下人不归
我寻月下人不归 2021-02-05 03:55

In python I usually loop through ranges simply by

for i in range(100): 
    #do something

but now I want to skip a few steps in the loop. Mo

4条回答
  •  北荒
    北荒 (楼主)
    2021-02-05 04:44

    You cannot alter the target list (i in this case) of a for loop. Use a while loop instead:

    while i < 10:
        i += 1
        if i == 2:
            i += 3
    

    Alternatively, use an iterable and increment that:

    from itertools import islice
    
    numbers = iter(range(10))
    for i in numbers:
        if i == 2:
            next(islice(numbers, 3, 3), None)  # consume 3
    

    By assigning the result of iter() to a local variable, we can advance the loop sequence inside the loop using standard iteration tools (next(), or here, a shortened version of the itertools consume recipe). for normally calls iter() for us when looping over a iterator.

提交回复
热议问题