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

时间:2012-12-05 17:02:04

标签: 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]

我尝试过使用递归,但使用长列表获取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])

6 个答案:

答案 0 :(得分:6)

理解是否有效?

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

或者可能使用reduce

reduce(
    lambda (sums, last), x: (sums+[x+last], x+last),
    l, ([], 0)
)[0]

或另一种方式:

reduce(lambda sums,x: sums+[x+sums[-1]], l[1:], l[:1])

答案 1 :(得分:1)

这是以函数式编程风格完成的累积总和:

def func(l):
   if len(l) < 2: return l
   sub = func(l[:-1])
   return sub + [sub[-1] + l[-1]]

print func([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

答案 2 :(得分:1)

减少怎么样?慢,但有趣,imo。

def func(p):
    for i in xrange(1, len(p)+1):
        yield reduce(lambda x, y: x + y, p[0:i])

>>> list(func(p))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

答案 3 :(得分:1)

这是我得到的,使用递归:

def f(L, n=0):
    # If the list is empty, that means we went through all the elements there
    if len(L)>0:
        # n is the last element in the sum list. Add to it the first remaining element
        n = n+L[0]
        # Return a list containing the newest item and those of the remaining elements
        return [n] + f(L[1:], n)
    else:
        # It it is empty, there are no more sums to calculate
        return []

答案 4 :(得分:0)

你能用numpy吗?

import numpy
numpy.cumsum([0,1,2,3,4,5,6,7,8,9])
array([ 0,  1,  3,  6, 10, 15, 21, 28, 36, 45])

答案 5 :(得分:-2)

l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
reduce(lambda x, y: x+y, l)