如何在 Python 中制作二维数组的副本? [英] How to make a copy of a 2D array in Python?

查看:25
本文介绍了如何在 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.

这篇关于如何在 Python 中制作二维数组的副本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆