如何在 Python 中复制2D 数组?

X是一个二维数组。我希望有一个新的变量 Y,它具有与数组 X相同的值。此外,任何进一步的 Y 操作都不应该影响 X 的值。

在我看来,使用 y = x是如此自然。但它不适用于数组。如果我这样做,然后改变 y,x 也会改变。我发现这个问题可以这样解决: y = x[:]

但它不适用于2D 数组,例如:

x = [[1,2],[3,4]]
y = x[:]
y[0][0]= 1000
print x

返回 [ [1000, 2], [3, 4] ]。如果我用 y = x[:][:]代替 y=x[:]也没有帮助。

有人知道什么是合适而简单的方法吗?

117115 次浏览

Try this:

from copy import copy, deepcopy
y = deepcopy(x)

I'm not sure, maybe copy() is sufficient.

In your case(since you use list of lists) you have to use deepcopy, because 'The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances): A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.'

Note that sample below is simply intended to show you an example(don't beat me to much) how deepcopy could be implemented for 1d and 2d arrays:

arr = [[1,2],[3,4]]


deepcopy1d2d = lambda lVals: [x if not isinstance(x, list) else x[:] for x in lVals]


dst = deepcopy1d2d(arr)


dst[1][1]=150
print dst
print arr

Using deepcopy() or copy() is a good solution. For a simple 2D-array case

y = [row[:] for row in x]

For 2D arrays it's possible use map function:

old_array = [[2, 3], [4, 5]]
# python2.*
new_array = map(list, old_array)
# python3.*
new_array = list(map(list, old_array))

I think np.tile also might be useful

>>> a = np.array([0, 1, 2])
>>> np.tile(a, 2)
array([0, 1, 2, 0, 1, 2])
>>> np.tile(a, (2, 2))
array([[0, 1, 2, 0, 1, 2],
[0, 1, 2, 0, 1, 2]])
>>> np.tile(a, (2, 1, 2))
array([[[0, 1, 2, 0, 1, 2]],
[[0, 1, 2, 0, 1, 2]]])