python - 使用 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 循环的情况下,最干净的方法是什么?
解决方案
你可以使用 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]
推荐阅读
- jquery - 如果窗口大小发生变化,撤消 jQuery 函数
- android - 使用自定义 recyclerview 适配器文件的 progressDialog 和 Toast 错误
- python - 字典 values() 方法只显示几个值
- sql-server - SQL Server 中的大整数键
- javascript - 为什么 CSS 在这个 JS 切换中不起作用?初学者问题
- ruby-on-rails - “heroku run rails db:seed”没有完成就停止(“状态从上到完成”)
- javascript - 从多个项目的 JSON 数据创建复杂表
- sql - 无法使用 IBM DB2 加载工具加载数据
- android - 有没有办法以编程方式获取属性的 id?
- html - 用图标完全替换 input type="button"