在不知道数组大小的情况下定义空数组



根据我的理解,当我们想要定义一个numpy数组时,我们必须定义它的大小。

然而,在我的例子中,我想定义一个numpy数组,然后根据我在for循环中的值扩展它。每次运行时,值的形状可能会有所不同。所以我不能提前定义numpy数组的形状。

有办法克服这个吗?

我想避免使用列表。

感谢
import numpy as np  
myArrayShape = 2
myArray = np.empty(shape=2)

注意,这会为数组中的每个元素生成随机值。

我认为numpy数组就像clang或c++中的数组一样,我的意思是当你制作numpy数组时,你根据你的请求(大小和dtype)分配内存。因此,最好在确定数组大小后再制作数组。

或者你可以试试numpy.appendhttps://numpy.org/doc/stable/reference/generated/numpy.append.html但我不认为这是更好的方式,因为它不断生成新的数组。

来自Octave (free-MATLAB)文档,https://octave.org/doc/v6.3.0/Advanced-Indexing.html

In cases where a loop cannot be avoided, or a number of values must be combined to form a larger matrix, it is generally faster to set the size of the matrix first (pre-allocate storage), and then insert elements using indexing commands. For example, given a matrix a,
[nr, nc] = size (a);
x = zeros (nr, n * nc);
for i = 1:n
x(:,(i-1)*nc+1:i*nc) = a;
endfor
is considerably faster than
x = a;
for i = 1:n-1
x = [x, a];
endfor
because Octave does not have to repeatedly resize the intermediate result.

同样的想法也适用于numpy。虽然您可以从(0,n)形数组开始,并通过concatenating(1,n)数组增长,但这比从(m,n)数组开始并赋值要慢得多。

有一个删除的答案,说明如何通过列表追加创建数组。这是强烈推荐的。