Я создаю генератор, который используется другой функцией, но мне все равно хотелось бы знать, сколько элементов было сгенерировано:
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()