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


time_interval=[4,6,12] 

i want sum numbers [4+0, 4+6, 4+6+12] in order list t=[4,10,22]. tried:

x=0 in (time_interval):     t1=time_interval[0]     t2=time_interval[1]+t1     t3=time_interval[2]+t2     print(t1,t2,t3)  4 10 22 4 10 22 4 10 22 

if you're doing numerical work arrays this, i'd suggest numpy, comes cumulative sum function cumsum:

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

numpy faster pure python kind of thing, see in comparison @ashwini's accumu:

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

but of course if it's place you'll use numpy, might not worth having dependence on it.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -