产生生成器和聚合结果的Python函数

威廉

用Python方式生成生成器也可以生成汇总结果的方式是什么?在元代码中,是这样的(但不是真实的,因为我的Python版本不支持混合yield和return):

def produce():
    total = 0
    for item in find_all():
        total += 1
        yield item

    return total

如我所见,我可以:

  1. 不是produce()生成器,而是将其传递给回调函数以在every上调用item
  2. 截止到现在yield每一个yield的总结果也是如此我宁愿不要仅在完成时就计算每个收益的中间结果。
  3. 发送一个dictas参数produce(),将使用汇总结果填充该参数
  4. 使用全局存储汇总结果。

他们似乎都不太吸引人...

注意 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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章