Python小练习:复制操作¶
作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/¶
1. 浅复制¶
In [1]:
# 复制的只是对象引用,而非对象本身
In [2]:
x = [53, 68, ["A", "B", "C"]]
In [3]:
y = x[:] # 浅复制
In [4]:
x, y
Out[4]:
In [5]:
x [2] [0] = "Q"
In [6]:
y [1] =40
In [7]:
x, y
Out[7]:
In [8]:
# x里面一变,y也跟着相应变,但y变了,x相应元素并不会变
2. 深复制¶
In [9]:
# 复制的是一个完全独立的副本
In [10]:
import copy
In [11]:
x = [53, 68, ["A", "B", "C"]]
In [12]:
y = copy.deepcopy(x) # 深复制
In [13]:
x, y
Out[13]:
In [14]:
x [2] [0] = "Q"
In [15]:
y [1] =40
In [16]:
x, y
Out[16]:
In [17]:
# 这里x,y只改变自己的,不会受到对方影响