Python 如何找到列表中数字的累积总和?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15889131/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the cumulative sum of numbers in a list?
提问by user2259323
time_interval = [4, 6, 12]
I want to sum up the numbers like [4, 4+6, 4+6+12]in order to get the list t = [4, 10, 22].
我想总结一下数字[4, 4+6, 4+6+12],以获得列表t = [4, 10, 22]。
I tried the following:
我尝试了以下方法:
t1 = time_interval[0]
t2 = time_interval[1] + t1
t3 = time_interval[2] + t2
print(t1, t2, t3) # -> 4 10 22
回答by Ashwini Chaudhary
In Python 2 you can define your own generator function like this:
在 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]
And in Python 3.2+ you can use itertools.accumulate():
在 Python 3.2+ 中,您可以使用itertools.accumulate():
In [1]: lis = [4,6,12]
In [2]: from itertools import accumulate
In [3]: list(accumulate(lis))
Out[3]: [4, 10, 22]
回答by abarnert
First, you want a running list of subsequences:
首先,您需要一个运行的子序列列表:
subseqs = (seq[:i] for i in range(1, len(seq)+1))
Then you just call sumon each subsequence:
然后你只需调用sum每个子序列:
sums = [sum(subseq) for subseq in subseqs]
(This isn't the most efficient way to do it, because you're adding all of the prefixes repeatedly. But that probably won't matter for most use cases, and it's easier to understand if you don't have to think of the running totals.)
(这不是最有效的方法,因为您要重复添加所有前缀。但这对于大多数用例可能无关紧要,如果您不必考虑,则更容易理解运行总数。)
If you're using Python 3.2 or newer, you can use itertools.accumulateto do it for you:
如果您使用的是 Python 3.2 或更新版本,您可以使用itertools.accumulate它来为您执行此操作:
sums = itertools.accumulate(seq)
And if you're using 3.1 or earlier, you can just copy the "equivalent to" source straight out of the docs (except for changing next(it)to it.next()for 2.5 and earlier).
如果你正在使用3.1或更早版本,你可以复制的“等同于”源直出的文档(除了改变next(it)以it.next()2.5和更早的版本)。
回答by MostafaR
Try this:
尝试这个:
result = []
acc = 0
for i in time_interval:
acc += i
result.append(acc)
回答by Chris Taylor
values = [4, 6, 12]
total = 0
sums = []
for v in values:
total = total + v
sums.append(total)
print 'Values: ', values
print 'Sums: ', sums
Running this code gives
运行此代码给出
Values: [4, 6, 12]
Sums: [4, 10, 22]
回答by gonz
lst = [4,6,12]
[sum(lst[:i+1]) for i in xrange(len(lst))]
If you are looking for a more efficient solution (bigger lists?) a generator could be a good call (or just use numpyif you really care about perf).
如果您正在寻找更有效的解决方案(更大的列表?),生成器可能是一个不错的选择(或者,numpy如果您真的关心性能,就可以使用)。
def gen(lst):
acu = 0
for num in lst:
yield num + acu
acu += num
print list(gen([4, 6, 12]))
回答by reptilicus
In [42]: a = [4, 6, 12]
In [43]: [sum(a[:i+1]) for i in xrange(len(a))]
Out[43]: [4, 10, 22]
This is slighltyfaster than the generator method above by @Ashwini for small lists
对于小列表,这比@Ashwini上面的生成器方法要快
In [48]: %timeit list(accumu([4,6,12]))
100000 loops, best of 3: 2.63 us per loop
In [49]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
100000 loops, best of 3: 2.46 us per loop
For larger lists, the generator is the way to go for sure. . .
对于较大的列表,生成器肯定是可行的方法。. .
In [50]: a = range(1000)
In [51]: %timeit [sum(a[:i+1]) for i in xrange(len(a))]
100 loops, best of 3: 6.04 ms per loop
In [52]: %timeit list(accumu(a))
10000 loops, best of 3: 162 us per loop
回答by askewchan
If you're doing much numerical work with arrays like this, I'd suggest numpy, which comes with a cumulative sum function cumsum:
如果您正在使用这样的数组进行大量数值工作,我建议您numpy使用累积求和函数cumsum:
import numpy as np
a = [4,6,12]
np.cumsum(a)
#array([4, 10, 22])
Numpy is often faster than pure python for this kind of thing, see in comparison to @Ashwini's accumu:
对于这种事情,Numpy 通常比纯 python 更快,请参见与@Ashwini 的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
But of course if it's the only place you'll use numpy, it might not be worth having a dependence on it.
但是当然,如果它是您将使用 numpy 的唯一地方,那么可能不值得依赖它。
回答by Vatine
Somewhat hacky, but seems to work:
有点hacky,但似乎有效:
def cumulative_sum(l):
y = [0]
def inc(n):
y[0] += n
return y[0]
return [inc(x) for x in l]
I did think that the inner function would be able to modify the ydeclared in the outer lexical scope, but that didn't work, so we play some nasty hacks with structure modification instead. It is probably more elegant to use a generator.
我确实认为内部函数能够修改y在外部词法范围中声明的函数,但这不起作用,所以我们用结构修改来代替一些讨厌的黑客。使用生成器可能更优雅。
回答by user3062149
Without having to use Numpy, you can loop directly over the array and accumulate the sum along the way. For example:
无需使用 Numpy,您可以直接遍历数组并一路累加总和。例如:
a=range(10)
i=1
while((i>0) & (i<10)):
a[i]=a[i-1]+a[i]
i=i+1
print a
Results in:
结果是:
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
回答by wonder.mice
Behold:
看:
a = [4, 6, 12]
reduce(lambda c, x: c + [c[-1] + x], a, [0])[1:]
Will output (as expected):
将输出(如预期):
[4, 10, 22]

