如何以功能方式对元素进行求和

use*_*805 4 python functional-programming

我正在尝试编写一个函数来映射列表的元素,以使用python以函数样式获取列表中元素和前一个元素的总和,例如:

func([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) = [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
Run Code Online (Sandbox Code Playgroud)

我试过使用递归,但得到RuntimeError: maximum recursion depth exceeded一个很长的列表:

def recursion_way(inlist, accu, summ):
    if len(inlist) == 0:
         return accu
    else:
        return recursion_way(inlist[1:], accu + [summ + inlist[0]], summ + inlist[0])
Run Code Online (Sandbox Code Playgroud)

Eri*_*ric 6

理解是否重要?

>>> [sum(l[:i]) for i, _ in enumerate(l)]
[0, 0, 1, 3, 6, 10, 15, 21, 28, 36]
Run Code Online (Sandbox Code Playgroud)

或者使用reduce:

reduce(
    lambda (sums, last), x: (sums+[x+last], x+last),
    l, ([], 0)
)[0]
Run Code Online (Sandbox Code Playgroud)

或者另一种方式:

reduce(lambda sums,x: sums+[x+sums[-1]], l[1:], l[:1])
Run Code Online (Sandbox Code Playgroud)