2016-12-07 124 views
1

我想找到一个巧妙的方法来实现以下目标:结合地图和减少

假装我有一个列表:

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

和一个简单的功能,只是增加了两个数字:

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

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

我可以直接减少列表

这给我的总和就好了。但是我想知道每次申请后的价值加。因此,使用类似于reduce的函数,我想返回以下数组:

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

有没有人有一种很酷的方式来实现这一点。我有使用某种形式的itertools解决方案如果可能的话:)

+1

你看过'itertools'函数吗?其中之一就是这样做。 – vaultah

+1

这被称为*累计和*。例如尝试'np.cumsum(x)'。可能是这个笨蛋http://stackoverflow.com/questions/15889131/how-to-find-the-cumulative-sum-of-numbers-in-a-list –

+0

相关:http://stackoverflow.com/questions/40009019/python-recursive-sum-list –

回答

0

有强烈的偏好既然你想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) 
+1

你可以使用'list(islice(accumlate(x),1,None))'来满足OP的预期输出 –

+0

我不知道如何设法错过积累。但这正是我需要的:P Bravo!并感谢你! – user2662833

+0

很高兴帮助:) – SerialDev