【发布时间】:2011-06-10 16:22:42
【问题描述】:
我正在创建一个被另一个函数消耗的生成器,但我仍然想知道生成了多少项:
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()
【问题讨论】:
-
当你说你创建生成器时,你的意思是你使用
yield定义一个函数还是你从一个理解或类似的地方创建一个生成器对象?