How do I skip a few iterations in a for loop

后端 未结 4 1980
我寻月下人不归
我寻月下人不归 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:37

    The best way is to assign the iterator a name - it is common have an iterable as opposed to an iterator (the difference being an iterable - for example a list - starts from the beginning each time you iterate over it). In this case, just use the iter() built-in function:

    numbers = iter(range(100))
    

    Then you can advance it inside the loop using the name. The best way to do this is with the itertools consume() recipe - as it is fast (it uses itertools functions to ensure the iteration happens in low-level code, making the process of consuming the values very fast, and avoids using up memory by storing the consumed values):

    from itertools import islice
    import collections
    
    def consume(iterator, n):
        "Advance the iterator n-steps ahead. If n is none, consume entirely."
        # Use functions that consume iterators at C speed.
        if n is None:
            # feed the entire iterator into a zero-length deque
            collections.deque(iterator, maxlen=0)
        else:
            # advance to the empty slice starting at position n
            next(islice(iterator, n, n), None)
    

    By doing this, you can do something like:

    numbers = iter(range(100))
    for i in numbers: 
        ...
        if some_check(i):
            consume(numbers, 3)  # Skip 3 ahead.
    

提交回复
热议问题