Python:在零数组中初始化 numpy 数组

Python: Initialize numpy arrays within an array of zeroes

在 Python 中,我试图在大小为 N x N 的数组中初始化 2 元素零数组。我正在使用的代码有效,但我正在寻找更高效和优雅的代码:

array1 = np.empty((N,N), dtype=object)
for i in range(N):
    for j in range(N):
        array1[i,j] = np.zeros(2, dtype=np.int)

在此先感谢您的帮助

据我了解,您可能应该使用 3D 数组:

import numpy as np
array1 = np.empty((N,N,2), dtype=object)

其中 returns 一个 N 行、N 列和 2 深度的数组。如果你想传递一个 (NxN) 数组来让我们说第一个深度,只需使用:

tmp = np.ones(N,N) #for instance
array1(:,:,0) = tmp