Pie*_*erz 10 python list-comprehension
使用列表推导(或其他紧凑方法)复制这个简单函数的最佳方法是什么?
import numpy as np
sum=0
array=[]
for i in np.random.rand(100):
sum+=i
array.append(sum)
Run Code Online (Sandbox Code Playgroud)
在Python 3中,您将使用itertools.accumulate():
from itertools import accumulate
array = list(accumulate(rand(100)))
Run Code Online (Sandbox Code Playgroud)
累积从第一个值开始,将输入迭代的值相加的运行结果:
>>> from itertools import accumulate
>>> list(accumulate(range(10)))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]
Run Code Online (Sandbox Code Playgroud)
您可以将另一个操作作为第二个参数传递; 这应该是一个可调用的,它获取累积的结果和下一个值,返回新的累积结果.该operator模块非常有助于为此类工作提供标准数学运算符; 您可以使用它来生成运行的乘法结果,例如:
>>> import operator
>>> list(accumulate(range(1, 10), operator.mul))
[1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
Run Code Online (Sandbox Code Playgroud)
该功能很容易向后移植到旧版本(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
Run Code Online (Sandbox Code Playgroud)