我想找到一個巧妙的方法來實現以下目標:結合地圖和減少
假裝我有一個列表:
> 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解決方案如果可能的話:)
你看過'itertools'函數嗎?其中之一就是這樣做。 – vaultah
這被稱爲*累計和*。例如嘗試'np.cumsum(x)'。可能是這個笨蛋http://stackoverflow.com/questions/15889131/how-to-find-the-cumulative-sum-of-numbers-in-a-list –
相關:http://stackoverflow.com/questions/40009019/python-recursive-sum-list –