如何在 Python 中制作二维数组的副本?
X
是一个二维数组.我想要一个与数组 X
具有相同值的新变量 Y
.此外,对 Y 的任何进一步操作都不应影响 X 的值.
X
is a 2D array. I want to have a new variable Y
that which has the same value as the array X
. Moreover, any further manipulations with Y should not influence the value of the X.
在我看来使用 y = x
很自然.但它不适用于数组.如果我这样做然后改变 y,x 也会改变.我发现问题可以这样解决:y = x[:]
It seems to me so natural to use y = x
. But it does not work with arrays. If I do it this way and then changes y, the x will be changed too. I found out that the problem can be solved like that: y = x[:]
但它不适用于二维数组.例如:
But it does not work with 2D array. For example:
x = [[1,2],[3,4]]
y = x[:]
y[0][0]= 1000
print x
返回 [ [1000, 2], [3, 4] ]
.如果我用 y = x[:][:]
替换 y=x[:]
也无济于事.
returns [ [1000, 2], [3, 4] ]
. It also does not help if I replace y=x[:]
by y = x[:][:]
.
有人知道什么是正确且简单的方法吗?
Does anybody know what is a proper and simple way to do it?
试试这个:
from copy import copy, deepcopy
y = deepcopy(x)
我不确定,也许 copy()
就足够了.
I'm not sure, maybe copy()
is sufficient.