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

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

    If you're doing much numerical work with arrays like this, I'd suggest numpy, which comes with a cumulative sum function cumsum:

    import numpy as np
    
    a = [4,6,12]
    
    np.cumsum(a)
    #array([4, 10, 22])
    

    Numpy is often faster than pure python for this kind of thing, see in comparison to @Ashwini's accumu:

    In [136]: timeit list(accumu(range(1000)))
    10000 loops, best of 3: 161 us per loop
    
    In [137]: timeit list(accumu(xrange(1000)))
    10000 loops, best of 3: 147 us per loop
    
    In [138]: timeit np.cumsum(np.arange(1000))
    100000 loops, best of 3: 10.1 us per loop
    

    But of course if it's the only place you'll use numpy, it might not be worth having a dependence on it.

提交回复
热议问题