[英]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
這給了我總和就好了。 但我想知道每次添加后的值。 所以使用類似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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.