5

リストの要素をマップして、リスト内の要素と前の要素の合計を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])
4

6 に答える 6

7

理解度は重要ですか?

>>> [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])
于 2012-12-05T17:04:41.903 に答える
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 []
于 2012-12-05T17:16:01.000 に答える
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])
于 2012-12-05T17:05:56.153 に答える
1

減らしてはどうですか?ゆっくりですが、面白いです。

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]
于 2012-12-05T17:08:29.280 に答える
0

ナンパ使えますか?

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])
于 2012-12-05T17:05:41.240 に答える
-2
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
reduce(lambda x, y: x+y, l)
于 2012-12-05T17:06:50.333 に答える