Length of a finite generator

前端 未结 3 857
野性不改
野性不改 2021-01-18 03:32

I have these two implementations to compute the length of a finite generator, while keeping the data for further processing:

def count_generator1(generator):         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-18 03:48

    If you have to do this, the first method is much better - as you consume all the values, itertools.tee() will have to store all the values anyway, meaning a list will be more efficient.

    To quote from the docs:

    This itertool may require significant auxiliary storage (depending on how much temporary data needs to be stored). In general, if one iterator uses most or all of the data before another iterator starts, it is faster to use list() instead of tee().

提交回复
热议问题