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

2024-04-29 01:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

time_interval = [4, 6, 12]

我想把像[4, 4+6, 4+6+12]这样的数字加起来,得到列表t = [4, 10, 22]

我尝试了以下方法:

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

Tags: 方法in列表fortime数字t1t3
3条回答

在Python 2中,您可以定义自己的生成器函数,如下所示:

def accumu(lis):
    total = 0
    for x in lis:
        total += x
        yield total

In [4]: list(accumu([4,6,12]))
Out[4]: [4, 10, 22]

在Python 3.2+中,您可以使用^{}

In [1]: lis = [4,6,12]

In [2]: from itertools import accumulate

In [3]: list(accumulate(lis))
Out[3]: [4, 10, 22]

请看:

a = [4, 6, 12]
reduce(lambda c, x: c + [c[-1] + x], a, [0])[1:]

将输出(如预期):

[4, 10, 22]

如果您对这样的数组进行了大量的数值计算,我建议使用^{},它带有一个累积和函数^{}

import numpy as np

a = [4,6,12]

np.cumsum(a)
#array([4, 10, 22])

对于这种情况,Numpy通常比纯python快,请参见与@Ashwini's ^{}的比较:

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的地方,那么依赖它可能是不值得的。

相关问题 更多 >