Skip to main content
 首页 » 编程设计

python之如何有效地创建一个多维 numpy 数组,其条目仅取决于一维索引

2025年05月04日12傻小

如何使用内置函数更有效地创建以下 numpy 数组?

import numpy as np 
MyArray = np.zeros([10,10,10,10,10]) 
for i in range(10): 
    for j in range(10): 
        for k in range(10): 
            for l in range(10): 
                for m in range(10): 
                    MyArray[i,j,k,l,m] = l 

如您所见,元素应仅依赖于其中一个维度索引。我尝试使用 numpy.tile但到目前为止还想不通。

请您参考如下方法:

看起来你在寻找 np.broadcast_to:

# build an array where l_vals[0,0,0,i,0] = i 
l_vals = np.arange(10).reshape(1, 1, 1, -1, 1) 
 
# duplicate that array, without copies, in the other axes 
l_grid = np.broadcast_to(l_vals, (10, 10, 10, 10, 10)) 

值得注意的是,broadcast_to 返回一个只读数组,因为元素实际上共享内存位置。如果你想在创建它之后写入它,那么你可以调用 np.copy,或者使用 tile 代替:

l_grid = np.tile(l_vals, (10, 10, 10, 1, 10)) 

您也可以将循环展平:

MyArray = np.zeros([10,10,10,10,10]) 
for l in range(10): 
    MyArray[:,:,:,l,:] = l