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

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

    This would be Haskell-style:

    def wrand(vtlg):
    
        def helpf(lalt,lneu): 
    
            if not lalt==[]:
                return helpf(lalt[1::],[lalt[0]+lneu[0]]+lneu)
            else:
                lneu.reverse()
                return lneu[1:]        
    
        return helpf(vtlg,[0])
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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]
    
    0 讨论(0)
提交回复
热议问题