2016-12-07 264 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