Skip to main content
 首页 » 编程设计

python之声明 numpy 矩阵的简洁方法

2025年05月04日14jpfss

声明一个 999x999 numpy 矩阵的简短易读方法是什么,其中每一行都是 [1,2,3,...,999]?最终的矩阵应该是:

[[1,2,3,...,999] 
[1,2,3,...,999] 
... 
[1,2,3,...,999]] 

请您参考如下方法:

您可以使用 numpy.tile :

import numpy as np 
 
res = np.tile(range(10), (5, 1)) 
 
print(res) 
 
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]) 

或者,您可以添加到零数组:

res = np.zeros((5, 10)) + range(10)