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

前端 未结 21 1935
挽巷
挽巷 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 03:04

    Without having to use Numpy, you can loop directly over the array and accumulate the sum along the way. For example:

    a=range(10)
    i=1
    while((i>0) & (i<10)):
        a[i]=a[i-1]+a[i]
        i=i+1
    print a
    

    Results in:

    [0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
    

提交回复
热议问题