Skip to main content
 首页 » 编程设计

python之没有 for 循环的 Numpy 数组

2024年12月31日6webabcd

array = np.empty(8,4) 
 
for I in range(8): 
   array[I] = I  

这可以不用for循环实现吗?我想知道其他方法

array = np.empty(8,4) 
for I in range(8): 
   array[I] = I  
 
[0,0,0,0] 
[1,1,1,1] 
    . 
    . 
    . 
[7,7,7,7] 

请您参考如下方法:

一种简单的方法是只使用np.repeat:

array = np.repeat(np.arange(8), 4).reshape(8, 4) 
 
array([[0, 0, 0, 0], 
       [1, 1, 1, 1], 
       [2, 2, 2, 2], 
       [3, 3, 3, 3], 
       [4, 4, 4, 4], 
       [5, 5, 5, 5], 
       [6, 6, 6, 6], 
       [7, 7, 7, 7]])