我正在创建一个被另一个函数使用的生成器,但我仍然想知道生成了多少项:
lines = (line.rstrip('\n') for line in sys.stdin)
process(lines)
print("Processed {} lines.".format( ? ))
我能想到的最好的办法是用一个保持计数的类包装生成器,或者把它翻过来,然后把()的东西发送进去。有没有一种优雅而有效的方法来查看一个生成器在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()
下面是另一种使用^{} 示例的方法:
希望这有帮助。
如果你不在乎你正在消耗发电机,你可以做:
通常,我只是把生成器变成一个列表,然后计算它的长度。如果您有理由认为这会消耗太多内存,那么您最好的选择似乎就是您自己建议的包装类。不过也不算太糟:
(最后一行用于与Python3.x的前向兼容性。)
相关问题 更多 >
编程相关推荐