使用列表理解(或其他紧凑方法)复制这个简单函数的最佳方法是什么?
import numpy as np
sum=0
array=[]
for i in np.random.rand(100):
sum+=i
array.append(sum)
最佳答案
在 Python 3 中,您将使用 itertools.accumulate()
:
from itertools import accumulate
array = list(accumulate(rand(100)))
Accumulate 产生从第一个值开始累加输入可迭代值的运行结果:
>>> from itertools import accumulate
>>> list(accumulate(range(10)))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
您可以将不同的操作作为第二个参数传递;这应该是一个可调用的,它接受累积的结果和下一个值,返回新的累积结果。 operator
module非常有助于为这类工作提供标准的数学运算符;您可以使用它来生成运行的乘法结果,例如:
>>> 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):
# 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
关于python - 用累加器列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20222485/