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

前端 未结 21 1628
挽巷
挽巷 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:43

    There could be many answers for this depending on the length of the list and the performance. One very simple way which I can think without thinking of the performance is this:

    a = [1, 2, 3, 4]
    a = [sum(a[0:x:1]) for x in range(len(a)+1)][1:]
    print(a)
    

    [1, 3, 6, 10]

    This is by using list comprehension and this may work fairly well it is just that here I am adding over the subarray many times, you could possibly improvise on this and make it simple!

    Cheers to your endeavor!

提交回复
热议问题