[英]Generating a list of unique numpy arrays
I'm trying to make a list of numpy ndarrays, similar to the following: 我正在尝试列出numpy ndarray,类似于以下内容:
>>> import numpy as np
>>> a = np.array([1,2,3])
>>> b = 3*[np.copy(a)]
>>> print b
[array([1, 2, 3]), array([1, 2, 3]), array([1, 2, 3])]
But each element of this list is an alias of the original array np.copy(a)
, so changing one element of any ndarray changes all of the other corresponding elements, ie: 但是此列表中的每个元素都是原始数组np.copy(a)
的别名,因此更改任何ndarray的一个元素都会更改所有其他对应的元素,即:
>>> b[0][0] = 0
>>> print b
[array([0, 2, 3]), array([0, 2, 3]), array([0, 2, 3])]
How can I make each of these arrays independent of each other, so that the above result would be: 我如何使这些数组彼此独立,以便上面的结果是:
[array([0, 2, 3]), array([1, 2, 3]), array([1, 2, 3])]
Doing 3*[np.copy(a)]
actually does one copy of a
and creates 3 references to this copy, so that you can not change only one because they are the same object. 做3*[np.copy(a)]
实际上做的一个副本a
,并创建3个引用此副本,这样,因为它们是同一个对象,你不能只有一个变化。 Doing this: 这样做:
b = [np.copy(a) for i in range(3)]
will create 3 independent copies. 将创建3个独立副本。
But it seems you should work with b as a 2D array, which you can achieve doing: 但是似乎您应该将b作为2D数组使用,您可以实现以下目的:
b = np.vstack((a for i in range(3)))
The reason why what you were trying didn't work is that 您尝试的方法不起作用的原因是
>>> b = 3*[np.copy(a)]
is essentially equivalent to 基本上等于
>>> c = np.copy(a)
>>> b = 3*[c]
In Python, c
is not the array, c
is, in this case, a reference to an array. 在Python, c
不是阵列, c
是,在这种情况下,数组的引用。 3*[c]
just copies that reference three times. 3*[c]
只需复制引用三次即可。 You could do, 你可以做
>>> b = [np.copy(a) for i in xrange(3)]
as sgpc mentions , or you could even do, 如sgpc所述 ,或者您甚至可以做到,
>>> b = [np.array([1,2,3]) for i in xrange(3)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.