How to find the cumulative sum of numbers in a list?

前端 未结 21 2093
挽巷
挽巷 2020-11-22 02:09
time_interval = [4, 6, 12]

I want to sum up the numbers like [4, 4+6, 4+6+12] in order to get the list t = [4, 10, 22].

21条回答
  •  我寻月下人不归
    2020-11-22 02:42

    In Python3, To find the cumulative sum of a list where the ith element is the sum of the first i+1 elements from the original list, you may do:

    a = [4 , 6 , 12]
    b = []
    for i in range(0,len(a)):
        b.append(sum(a[:i+1]))
    print(b)
    

    OR you may use list comprehension:

    b = [sum(a[:x+1]) for x in range(0,len(a))]
    

    Output

    [4,10,22]
    

提交回复
热议问题