python - 用累加器列表理解

标签 python list-comprehension

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

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/

相关文章:

python - 如何从工作线程导入 Python 异步模块?

python - 如何检查 SQLAlchemy session 是否脏

python - 一个用于复制来自文件的行的衬里 (Python)

使用类变量的 Python 列表理解抛出 NameError

python - 如何构建可以在 Web UI 上运行的 Python 脚本

python - 使用生成器表达式返回多个值

python - 如何编写列表理解,包括 If Else 条件

python - 在 Python 中为数据创建直方图

python - 使用列表中的项目更改嵌套字典中的值?

Python Pandas 更改索引数据框