更新时间:2023-11-28 21:03:22
为此设置一个for循环可能会相对昂贵,请记住,Python中的 for 循环从根本上是连续执行简单的赋值语句;您将执行 n (生成器中的项目数)分配,但此后只会丢弃分配目标.
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.
您可以改为将生成器的长度设为零.以C速度消耗,并且不像list
和实现迭代器/生成器的其他可调用项那样用尽内存:
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)
取自consume
itertools配方.
Taken from the consume
itertools recipe.