如何找到列表中数字的累积总和? [英] How to find the cumulative sum of numbers in a list?

查看:21
本文介绍了如何找到列表中数字的累积总和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案

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

这篇关于如何找到列表中数字的累积总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆