首页 > 解决方案 > 使用 Numpy 的数值系列

问题描述

我想用 Numpy 制作一个系列。例如,从n = 2我要创建系列的值开始:

terms = numpy.array([2, 6, 24, 120, 720,...])

其中每个连续项将前一项乘以系列中的第一项,并添加到递增索引中。例如,上面将是

terms[1] = terms[0] * (terms[0] + 1)
terms[2] = terms[1] * (terms[0] + 2)
terms[3] = terms[2] * (terms[0] + 3)
terms[4] = terms[3] * (terms[0] + 4)

这可以用 Numpy 完成吗?如果不是,那么在没有 for 循环的情况下,最干净的方法是什么?

标签: pythonnumpy

解决方案


你可以使用 np.accumulate:

import numpy as np

size  = 5
n     = 2
terms = np.multiply.accumulate(np.arange(size) + n)

[  2   6  24 120 720]

您也可以在没有 numpy 的情况下执行此操作(尽管速度较慢):

from itertools import accumulate

size  = 5
n     = 2
terms = [*accumulate(range(n,size+n),lambda a,b:a*b)]

[2, 6, 24, 120, 720]

推荐阅读