Cumsum 在 python 中返回向量

Cumsum returning a vector in python

我有我的数组,说:[10, 6, 4, 12]。 我有兴趣找到累积和的向量,即: [10, 16, 20, 32]。 显而易见的方法是使用 for 循环:

r = []
for ind in range(4):
  r.append(s[ind])  # s is [10, 6, 4, 12]
r = cumsum(r)

但是,这似乎效率很低。我想问一下是否有预定义的函数或者我应该在cumsum中指定特定的参数。

有很多方法,比如np.cumsum或python 3.2+你可以使用itertools.accumulate

通过 Itertool:

l = [10, 6, 4, 12]

from itertools import accumulate

print(list(accumulate(l)))

输出:

[10, 16, 20, 32]

使用 numpy:

import numpy as np

print(np.cumsum(l))

输出:

[10, 16, 20, 32]

无限制解决方案:

s = [10, 6, 4, 12]
r = [sum(s[:i+1]) for i in range(len(s))]

输出:

[10, 16, 20, 32]