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]
.
I tried the following:
for i 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
This would be Haskell-style:
If You want a pythonic way without numpy working in 2.7 this would be my way of doing it
now let's try it and test it against all other implementations
Running this code gives
If you're doing much numerical work with arrays like this, I'd suggest
numpy
, which comes with a cumulative sum functioncumsum
:Numpy is often faster than pure python for this kind of thing, see in comparison to @Ashwini's
accumu
:But of course if it's the only place you'll use numpy, it might not be worth having a dependence on it.
Try this:
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).