如何找到列表中数字的累加和? [英] How to find the cumulative sum of numbers in a list?
本文介绍了如何找到列表中数字的累加和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
time_interval = [4, 6, 12]
我想对[4, 4+6, 4+6+12]
之类的数字求和,以获得列表t = [4, 10, 22]
.
I want to sum up the numbers like [4, 4+6, 4+6+12]
in order to get the list t = [4, 10, 22]
.
我尝试了以下操作:
t1 = time_interval[0]
t2 = time_interval[1] + t1
t3 = time_interval[2] + t2
print(t1, t2, t3) # -> 4 10 22
推荐答案
如果您要对此类数组进行大量数值工作,我建议 cumsum
:
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通常比纯python更快,请参见与 @Ashwini的accumu
相比:
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
但是,当然,如果这是您唯一使用numpy的地方,则可能不值得依赖它.
But of course if it's the only place you'll use numpy, it might not be worth having a dependence on it.
这篇关于如何找到列表中数字的累加和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文