Python - 列表中某些数字的总和

时间:2015-03-22 10:48:44

标签: python list sum reverse

假设我有一个列表(此列表可以有任意数量的数字):

a = [2,5,2,4]

我想反过来说:

a[::-1]

给了我[4,2,5,2]。 然后我想实现第一个数字的总和,前2个数字的总和,前3个数字的总和等。 所以我应该得到:

[4,6,11,13]

1 个答案:

答案 0 :(得分:0)

您需要使用for循环。

>>> m = []              # creates an empty list
>>> j = 0               # Declare a variable and assign 0 to it. This would be used to store the calculated intermediate sum.
>>> for i in a[::-1]:   # iterate over each item in the reversed list. 
        j += i          # For each iteration, add the element with the j value and then assign the result back to the variable j.
        m.append(j)     # Append the content of j to the list m.


>>> m
[4, 6, 11, 13]