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

前端 未结 21 1599
挽巷
挽巷 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

    In [42]: a = [4, 6, 12]
    
    In [43]: [sum(a[:i+1]) for i in xrange(len(a))]
    Out[43]: [4, 10, 22]
    

    This is slighlty faster than the generator method above by @Ashwini for small lists

    In [48]: %timeit list(accumu([4,6,12]))
      100000 loops, best of 3: 2.63 us per loop
    
    In [49]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
      100000 loops, best of 3: 2.46 us per loop
    

    For larger lists, the generator is the way to go for sure. . .

    In [50]: a = range(1000)
    
    In [51]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
      100 loops, best of 3: 6.04 ms per loop
    
    In [52]: %timeit list(accumu(a))
      10000 loops, best of 3: 162 us per loop
    

提交回复
热议问题