用累加器理解列表

问题描述 投票:0回答:4

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

import numpy as np

sum=0
array=[]
for i in np.random.rand(100):
   sum+=i
   array.append(sum)
python list-comprehension
4个回答
11
投票

在 Python 3 中,您将使用

itertools.accumulate()
:

from itertools import accumulate

array = list(accumulate(rand(100)))

Accumulate 产生从第一个值开始将输入 iterable 的值相加的运行结果:

>>> from itertools import accumulate
>>> list(accumulate(range(10)))
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45]

您可以将不同的操作作为第二个参数传递;这应该是一个可调用的,它接受累积的结果和下一个值,返回新的累积结果。

operator
模块 非常有助于为此类工作提供标准的数学运算符;你可以用它来产生一个运行的乘法结果,例如:

>>> 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

4
投票

由于您已经在使用

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])

1
投票

好吧,你说你不想要

numpy
但无论如何这是我的解决方案。 在我看来,你只是简单地求和,因此使用
cumsum()
函数。

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

举个随机的例子

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

0
投票

这里有一个概念滥用了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]
© www.soinside.com 2019 - 2024. All rights reserved.