python 使用累加器的列表解析

f2uvfpb9  于 2023-03-11  发布在  Python
关注(0)|答案(5)|浏览(130)

使用列表解析(或其他紧凑方法)复制这个简单函数的最佳方法是什么?

import numpy as np

sum=0
array=[]
for i in np.random.rand(100):
   sum+=i
   array.append(sum)
pobjuy32

pobjuy321#

在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或Python 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
fivyi3re

fivyi3re2#

由于您已经在使用numpy,因此可以使用cumsum

>>> from numpy.random import rand
>>> x = rand(10)
>>> x
array([ 0.33006219,  0.75246128,  0.62998073,  0.87749341,  0.96969786,
        0.02256228,  0.08539008,  0.83715312,  0.86611906,  0.97415447])
>>> x.cumsum()
array([ 0.33006219,  1.08252347,  1.7125042 ,  2.58999762,  3.55969548,
        3.58225775,  3.66764783,  4.50480095,  5.37092001,  6.34507448])
vfhzx4xs

vfhzx4xs3#

好吧,你说你不想要numpy,但这是我的解决方案。在我看来,你只是简单地取累积和,因此使用cumsum()函数。

import numpy as np
result = np.cumsum(some_array)

举个随机的例子

result = np.cumsum(np.random.uniform(size=100))
fwzugrvs

fwzugrvs4#

这里有一个概念滥用了python 3.8中引入的:=“walrus operator”的初衷。它将变量作为更大表达式的一部分进行赋值。我对这个概念的印象是,它的意图是保存用户在“if”的测试部分进行计算,然后在可执行部分再次进行计算。但是它不是if的本地变量,因此在定义变量之后,您可以随时使用它。因此,这个方法在列表解析中使用一个始终为True的if,作为进行重新赋值的位置。不幸的是,“+:=”不是一个运算符,因此您必须进行长手加法赋值,而不是+=:

import numpy as np

sum=0
array=[sum for i in np.random.rand(100) if (sum:=sum+i) or True]
xmjla07d

xmjla07d5#

对上述答案的更新,找到了一个更简单,更好的方法。不知道为什么我之前没有想到。使用海象操作符:=的项目总是包含在()中,有一个返回,不像常规赋值。所以在命令行中,test=0静默执行,但(test:=0)将0打印到屏幕上。所以在这方面,它就像一个函数,因为它有一个返回。所以它可以进入列表压缩的内容部分,而不是在带有或True的一次性“if”中使用它。
所以代码变为:

import numpy as np

sum=0
array=[(sum:=sum+i) for i in np.random.rand(100)]

相关问题