python - 如何计算其他代码消耗的生成器中的项目

标签 python count generator

我正在创建一个由另一个函数使用的生成器,但我仍然想知道生成了多少项:

lines = (line.rstrip('\n') for line in sys.stdin)
process(lines)
print("Processed {} lines.".format( ? ))

我能想到的最好的方法是用一个保持计数的类来包装生成器,或者可能将它翻过来然后 send() 里面的东西。有没有一种优雅有效的方法来查看一个生成器有多少项目当您不是在 Python 2 中使用它的人时生成?

编辑:这是我最终得到的:

class Count(Iterable):
    """Wrap an iterable (typically a generator) and provide a ``count``
    field counting the number of items.

    Accessing the ``count`` field before iteration is finished will
    invalidate the count.
    """
    def __init__(self, iterable):
        self._iterable = iterable
        self._counter = itertools.count()

    def __iter__(self):
        return itertools.imap(operator.itemgetter(0), itertools.izip(self._iterable, self._counter))

    @property
    def count(self):
        self._counter = itertools.repeat(self._counter.next())
        return self._counter.next()

最佳答案

如果你不关心你正在消耗生成器,你可以这样做:

sum(1 for x in gen)

关于python - 如何计算其他代码消耗的生成器中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6309277/

相关文章:

Python从其他文件导入变量

python - Gensim Word2Vec 从预训练模型中选择次要的词向量集

go - 检查 channel 的值

python - 带有列表生成器的 numpy fromiter

c++ - 我正在尝试生成随机数,但每次出现错误 ‘ranf’ 未在此范围内声明

python - 正向/反向运动学计算 2DOF python

python - 使用 DefaultAzureCredential 在本地向 Azure Key Vault 进行身份验证

计算 C 中 char 数组的离散值

mysql - 计算 MySQL 文本列中的单词

MySQL:计算某些值