除了最终结果之外,如何获取`reduce`的所有中间值?

How to get all intermediary values of `reduce` in addition to the final result?

调用functools.reduce returns只有最后的结果:

>>> from functools import reduce
>>> a = [1, 2, 3, 4, 5]
>>> f = lambda x, y: x + y
>>> reduce(f, a)
15

不是自己写一个循环,是否存在一个函数也returns中间值?

[3, 6, 10, 15]

(这只是一个简单的示例,我并不是要计算累计和 - 该解决方案应该适用于任意 af。)

您可以使用 itertools.accumulate():

>>> from itertools import accumulate
>>> list(accumulate([1, 2, 3, 4, 5], lambda x, y: x+y))[1:]
[3, 6, 10, 15]

注意参数的顺序相对于functools.reduce()进行了切换。

此外,默认的 func(第二个参数)是一个总和(如 operator.add),因此在您的情况下,它在技术上是可选的:

>>> list(accumulate([1, 2, 3, 4, 5]))[1:]  # default func: sum
[3, 6, 10, 15]

最后,值得注意的是 accumulate() 将包含序列中的第一项,因此结果是从上面的 [1:] 索引的。


在您的编辑中,您注意到...

This is only a simple example, I'm not trying to calculate the cumulative sum - the solution should work for arbitrary a and f.

accumulate() 的好处在于它可以灵活处理它所需要的可调用对象。它只需要一个作为两个参数函数的可调用对象。

例如,内置 max() 满足:

>>> list(accumulate([1, 10, 4, 2, 17], max))
[1, 10, 10, 10, 17]

这是使用不必要的 lambda 的一种更长的形式:

>>> # Don't do this
>>> list(accumulate([1, 10, 4, 2, 17], lambda x, y: max(x, y)))
[1, 10, 10, 10, 17]
import numpy as np
x=[1, 2, 3, 4, 5]
y=np.cumsum(x) # gets you the cumulative sum
y=list(y[1:]) #  remove the first number
print(y)
#[3, 6, 10, 15]