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

查看:359
本文介绍了如何使Python中的二维数组的副本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

X 是一个二维数组。我想有一个新的变量即具有相同的值作为数组 X 。此外,为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 [:] [:]

有谁知道什么是做一个适当的和简单的方式?

Does anybody know what is a proper and simple way to do it?

推荐答案

试试这个:

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

我不知道,也许 复制() 是足够的。

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

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