Simpler way to run a generator function without caring about items

前端 未结 4 1247
温柔的废话
温柔的废话 2020-12-17 17:20

I have some use cases in which I need to run generator functions without caring about the yielded items.
I cannot make them non-generaor functions because in other use c

4条回答
  •  借酒劲吻你
    2020-12-17 17:46

    Setting up a for loop for this could be relatively expensive, keeping in mind that a for loop in Python is fundamentally successive execution of simple assignment statements; you'll be executing n (number of items in generator) assignments, only to discard the assignment targets afterwards.

    You can instead feed the generator to a zero length deque; consumes at C-speed and does not use up memory as with list and other callables that materialise iterators/generators:

    from collections import deque
    
    def exhaust(generator):
        deque(generator, maxlen=0)
    

    Taken from the consume itertools recipe.

提交回复
热议问题