如何添加到numpy的不同尺寸的数组项在for循环中(类似于Matlab的单元阵列)? [英] How to add to numpy array entries of different size in a for loop (similar to Matlab's cell arrays)?
问题描述
我想实现一个analouge在Python \\ numpy的Matlab的单元阵列。
Matlab的code会去这样的:
I'm trying to implement an analouge to Matlab's cell array in python \ numpy. The Matlab code would go like that :
for n=1:10
C{n} = rand(1,n);
end
请注意,每个电池元件具有不同的长度。现在,在numpy的:
Note that each cell element has a different length. Now in 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?
推荐答案
在最简单的情况下,你可以只使用一个标准的Python列表。它们类似于Matlab的电池阵列pretty,你可以用它们来存储任何东西:
In most simple cases, you could just use a standard Python list. They are pretty similar to Matlab cell-arrays, you can use them to store anything:
C = []
for n in np.arange(10):
C.append(np.random.rand(1,n))
这将是一个很好的选择,如果该列表不是太长,如果它只有一个尺寸(所以只是一个载体)。请注意,在Python中,你通常不会pre-分配的最终尺寸的列表,而只是追加到一个空列表。 Python列表是为追加到最后优化,他们已经做的引擎盖下的某种pre-分配。
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 lists are optimized for appending to the end, they already do some sort of pre-allocation under the hood.
如果你正在翻译Matlab的code具有多层面的细胞阵列,或者那些都是非常大的,你可以使用numpy的阵列, DTYPE =对象
:
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
:
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)
这篇关于如何添加到numpy的不同尺寸的数组项在for循环中(类似于Matlab的单元阵列)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!