制作生成聚合结果的生成器的 Pythonic 方法是什么?在元代码中,是这样的(但不是真的,因为我的 Python 版本不支持混合 yield 和 return):
def produce():
total = 0
for item in find_all():
total += 1
yield item
return total
在我看来,我可以:
- 不是让
produce()
成为一个生成器,而是给它传递一个回调函数来调用每个item
。 - 对于每个
yield
,还有yield
到目前为止的聚合结果。我宁愿不计算每个 yield 的中间结果,只在完成时计算。 - 发送一个
dict
作为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
关于生成生成器和聚合结果的 Python 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41927314/