用Python方式生成生成器也可以生成汇总结果的方式是什么?在元代码中,是这样的(但不是真实的,因为我的Python版本不支持混合yield和return):
def produce():
total = 0
for item in find_all():
total += 1
yield item
return total
如我所见,我可以:
produce()
生成器,而是将其传递给回调函数以在every上调用item
。yield
,每一个yield
的总结果也是如此。我宁愿不要仅在完成时就计算每个收益的中间结果。dict
as参数produce()
,将使用汇总结果填充该参数。他们似乎都不太吸引人...
注意 total
是一个简单的示例,我的实际代码需要复杂的聚合。我需要在produce()
完成之前获得中间结果,因此需要一个生成器。
也许您不应该使用生成器,而应该使用迭代器。
def findall(): # no idea what your "find_all" does so I use this instead. :-)
yield 1
yield 2
yield 3
class Produce(object):
def __init__(self, iterable):
self._it = iterable
self.total = 0
def __iter__(self):
return self
def __next__(self):
self.total += 1
return next(self._it)
next = __next__ # only necessary for python2 compatibility
也许最好用一个例子来看一下:
>>> it = Produce(findall())
>>> it.total
0
>>> next(it)
1
>>> next(it)
2
>>> it.total
2
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句