我正在创建一个由另一个函数使用的生成器,但我仍然想知道生成了多少项:
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/