[英]How to add to numpy array entries of different size in a for loop (similar to Matlab's cell arrays)?
I'm trying to implement an analouge to Matlab's cell array in python \\ numpy. 我正在尝试在python \\ numpy中对Matlab的单元数组实现一个analouge。 The Matlab code would go like that :
Matlab代码就是这样的:
for n=1:10
C{n} = rand(1,n);
end
Note that each cell element has a different length. 注意,每个单元元素具有不同的长度。 Now in numpy:
现在在numpy:
for n in np.arange(10):
C[n] = np.random.rand(1,n)
and I get an error, what can I do to implement this? 我得到一个错误,我该怎么做才能实现这个?
In most simple cases, you could just use a standard Python list. 在大多数简单的情况下,您可以使用标准的Python列表。 They are pretty similar to Matlab cell-arrays, you can use them to store anything:
它们非常类似于Matlab单元格数组,您可以使用它们来存储任何内容:
C = []
for n in np.arange(10):
C.append(np.random.rand(1,n))
This would be a good option if the list is not too long and if it only has a single dimension (so just a vector). 如果列表不是太长并且它只有一个维度(所以只是一个向量),这将是一个很好的选择。 Note that in Python, you typically do not pre-allocate a list of the final size, but simply append to an empty list.
请注意,在Python中,您通常不会预先分配最终大小的列表,而只是附加到空列表。 Python lists are optimized for appending to the end, they already do some sort of pre-allocation under the hood.
Python列表经过优化以便追加到最后,他们已经在底层进行了某种预分配。
If you are translating Matlab code with cell-arrays of multiple dimensions, or ones that are very large, you could use numpy arrays with dtype=object
: 如果要将Matlab代码与多维度的单元格数组或非常大的单元格数组进行转换,则可以使用带有
dtype=object
numpy数组:
m, n = 3, 6
C = np.empty((m, n), dtype=object)
for i in xrange(m):
for j in xrange(n):
C[i, j] = np.random.rand(i, j)
You are using a list there. 你在那里使用一个列表。 So, before indexing into it with
[n]
inside that loop, you need to initialize that list. 因此,在使用该循环内的
[n]
索引到它之前,您需要初始化该列表。 One of the ways to initialize a list is like this - 初始化列表的方法之一是这样的 -
C = [None]*10 # Here 10 is the length of the list
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.