天天看点

浅谈python 深拷贝与浅拷贝

1、浅拷贝

(1)定义

浅拷贝是指重新分配一份内存空间给新变量,新变量的元素是原变量的的元素的引用。

(2)实现方式

1)通过类型构造器

l1 = [1, 2, 3]
l2 = list(l1)
print l1 == l2 # True
print l1 is l2 # False

s1 = (1, 2, 3)
s2 = set(s1)
print s1 == s2 # True
print s1 is s2 # False

l1 = [[1, 2], (3, 4), 5]
l2 = list(l1)
print l1==l2 # True
print l1 is l2 # False

print l1[0] is l2[0] # True
print l1[1] is l2[1] # True

# 注意可变变量list和不可变变量set的区别
l1[0].append(3)
print l1 # [[1, 2, 3], (3, 4), 5]
print l2 # [[1, 2, 3], (3, 4), 5]

l1[1].append(5)
print l1 # [[1, 2, 3], (3, 4, 5), 5]
print l2 # [[1, 2, 3], (3, 4), 5]
           

2)通过切片操作,对列表来说,

l1 = [1, 2, 3]
l2 = l1[:]
print l1 == l2 # True
print l1 is l2 # False


s1 = (1, 2, 3)
s2 = s1[:]
print s1 == s2 # True
print s1 is s2 # False
           

3)通过copy 模块的copy方法

import copy

l1 = [1, 2, 3]
l2 = copy.copy(l1)
print l1 == l2 # True
print l1 is l2 # False


s1 = (1, 2, 3)
s2 = copy.copy(s1)
print s1 == s2 # True
print s1 is s2 # False
           

2、深拷贝

 (1)定义

深拷贝是指重新分配一份内存空间给新变量,并以递归的方式将原变量的元素重新拷贝一份到新变量中,因此新变量中保存的是全新的元素,不再是原变量元素的引用,因此原变量与新变量没有任何联系,原变量做的任何修改也不会同步到新变量中。

(2)实现方式

1)通过copy模块的deepcopy方法

import copy
l1 = [1, 2, 3]
l2 = copy.deepcopy(l1)
print l1 == l2 # True
print l1 is l2 # False


l1 = [[1, 2], (3, 4), 5]
l2 = copy.deepcopy(l1)
print l1==l2 # True
print l1 is l2 # False

print l1[0] is l2[0] # False
print l1[1] is l2[1] # False

l1[0].append(3)
print l1 # [[1, 2, 3], (3, 4), 5]
print l2 # [[1, 2], (3, 4), 5]

l1[1].append(5)
print l1 # [[1, 2, 3], (3, 4, 5), 5]
print l2 # [[1, 2], (3, 4), 5]
           

 3、"==" 和 "is"的区别

(1)"==" 判断的是对象的值是否相等

(2)"is" 判断的是对象的地址是否相等,即通过 id(object)获得的身份标识。

4、"=" 赋值运算符

l1 = [1, 2, 3]
l2 = l1

print l1 is l2 # True,此时 l1和l2指向同一个地址,在这个地址上做的任何改变都会更新到l1,l2