You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效实现生成多列重复序列的numpy数组生成函数?

高效生成重复列的Numpy数组实现建议

需求:实现函数gen_array(start, end, n_cols),生成一个包含n_cols列的数组,每列均为从start(包含)到end(不包含)的连续序列。示例如下:

>>> gen_array(20, 25, 3)
array([[20, 20, 20],
       [21, 21, 21],
       [22, 22, 22],
       [23, 23, 23],
       [24, 24, 24]])

初始朴素实现:

import numpy as np

def gen_array(start, end, n_columns):
    a = np.arange(start, end).reshape(end-start, 1) # 创建从start到end的列向量
    return np.dot(a, [np.ones(n_columns)])          # 复制到n_columns列

(注:np.dot会将值转换为浮点数,此情况可接受,非强制要求)

希望找到更高效、更符合numpy风格的实现方式。


更新:
基于建议使用np.tile的方案,当前最优实现如下:

import numpy as np

def gen_array(start, end, n_cols):
    return np.tile(np.arange(start, end).reshape(-1, 1), (1, n_cols))

该实现简洁高效,符合numpy的使用习惯。


内容的提问来源于stack exchange,提问作者fearless_fool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:05:12