结合 map 和 reduce

Combining map and reduce

我想找到一种巧妙的方法来实现以下目标:

假设我有一个列表:

> x = [1, 2, 3, 4, 5]

还有一个简单的函数,只添加两个数字:

> def add(a, b)
      return a+b

我可以通过以下方式直接缩减列表 x

> sum = reduce(add, x)
> print(sum)
15

这给了我很好的总和。但我想知道 每次应用 add 后的值。所以使用类似于 reduce 的函数,我想取回以下数组:

> result = SOME_FUNCTION(add, x)
> print(result)
[3, 6, 10, 15]

有没有人有实现这一目标的绝妙方法。如果可能的话,我非常喜欢使用某种形式的 itertools 解决方案 :)

因为你想要 itertools

from itertools import accumulate
list(accumulate(x))
Out [130]:
[1, 3, 6, 10, 15]

或者生成器循环

def cumsum(x):
    total = 0
    for x in it:
        total += x
        yield total
list(cumsum(x))
Out [129]:
[1, 3, 6, 10, 15]

或者就像大卫提到的那样:

np.cumsum(x)
Out [123]:
array([ 1,  3,  6, 10, 15], dtype=int32)