累加器的列表理解 [英] List comprehension with an accumulator
问题描述
使用列表理解(或另一种紧凑的方法)来复制此简单功能的最佳方法是什么?
What is the best way to replicate this simple function using a list comprehension (or another compact approach)?
import numpy as np
sum=0
array=[]
for i in np.random.rand(100):
sum+=i
array.append(sum)
推荐答案
In Python 3, you'd use itertools.accumulate()
:
from itertools import accumulate
array = list(accumulate(rand(100)))
Accumulate产生从第一个值开始将所有可迭代输入值相加的运行结果:
Accumulate yields the running result of adding up the values of the input iterable, starting with the first value:
>>> from itertools import accumulate
>>> list(accumulate(range(10)))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
您可以传递另一个操作作为第二个参数;这应该是一个可调用的方法,该方法可以使用累积结果和下一个值,并返回新的累积结果. operator
模块在为此类工作;您可以使用它来产生连续的乘法结果,例如:
You can pass in a different operation as a second argument; this should be a callable that takes the accumulated result and the next value, returning the new accumulated result. The operator
module is very helpful in providing standard mathematical operators for this kind of work; you could use it to produce a running multiplication result for example:
>>> import operator
>>> list(accumulate(range(1, 10), operator.mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
该功能非常容易,可以向后移植到旧版本(Python 2,Python 3.0或3.1):
The functionality is easy enough to backport to older versions (Python 2, or Python 3.0 or 3.1):
# Python 3.1 or before
import operator
def accumulate(iterable, func=operator.add):
'Return running totals'
# accumulate([1,2,3,4,5]) --> 1 3 6 10 15
# accumulate([1,2,3,4,5], operator.mul) --> 1 2 6 24 120
it = iter(iterable)
total = next(it)
yield total
for element in it:
total = func(total, element)
yield total
这篇关于累加器的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!