且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何找到列表中数字的累积总和?

更新时间:2023-02-10 22:18:02

如果您正在使用这样的数组进行大量数值工作,我建议您使用 numpy,带有累积求和函数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.