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

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

    lst = [4,6,12]
    
    [sum(lst[:i+1]) for i in xrange(len(lst))]
    

    If you are looking for a more efficient solution (bigger lists?) a generator could be a good call (or just use numpy if you really care about perf).

    def gen(lst):
        acu = 0
        for num in lst:
            yield num + acu
            acu += num
    
    print list(gen([4, 6, 12]))
    

提交回复
热议问题