python - 有限生成器的长度

标签 python generator

我有这两个实现来计算有限生成器的长度,同时保留数据以供进一步处理:

def count_generator1(generator):
    '''- build a list with the generator data
       - get the length of the data
       - return both the length and the original data (in a list)
       WARNING: the memory use is unbounded, and infinite generators will block this'''
    l = list(generator)
    return len(l), l

def count_generator2(generator):
    '''- get two generators from the original generator
       - get the length of the data from one of them
       - return both the length and the original data, as returned by tee
       WARNING: tee can use up an unbounded amount of memory, and infinite generators will block this'''
    for_length, saved  = itertools.tee(generator, 2)
    return sum(1 for _ in for_length), saved

两者都有缺点,但都能胜任。有人可以对它们发表评论,甚至提供更好的选择吗?

最佳答案

如果您必须这样做,第一种方法要好得多 - 当您使用所有值时,itertools.tee() 无论如何都必须存储所有值,这意味着列表将是效率更高。

引自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().

关于python - 有限生成器的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18014437/

相关文章:

python - Python 内置函数 `all` 和 `any` 的 Perl 挂件

python - 为 OOV 词添加新向量的正确方法

java - 用Java制作一个名称生成器,将生成的字符数量限制为12个,但不会截断单词?

javascript - 为什么递归生成器函数在 ES2015 中不起作用?

python - 如何从 Taxid 获取分类等级名称?

python - 检测是否提供了可选参数(可能包括 None)

java - 使用 GWT 生成器修改现有类

python - 控制嵌套列表/字符串的递归(不检查类型)

修改列表中包含特定数量(不仅仅是字符)的元素的 Pythonic 方法

python - 为什么keras序列的一个实例会永远迭代?