python 中深拷贝和浅拷贝的区别

时间:2022-05-06 02:37:29

  通俗的理解,浅就是外面,深就是里面。浅拷贝的意思就是只拷贝外面的一层,深拷贝就是拷贝的里面的所有。

看两段代码:

元组:

#!/usr/bin/env/python
# -*-coding:utf-8-*-
# authour:xiapmin_pei

import copy
#定义一个元组,元组里面有一个列表,可以理解成内部
atuple=(1,2,3,[4,5])
#将元组赋值给b
b = atuple
#浅拷贝
c = copy.copy(atuple)
#深拷贝
d = copy.deepcopy(atuple)
#打印每个对象的值
print "b is {0},c is {1},d is {2}".format(b,c,d)

#改变atuple里面内嵌的列表,给列表增加一个6
atuple[3].append(6)

print "b is {0},c is {1},d is {2}".format(b,c,d)

结果:可以看出来,将atuple赋值给b,b和atuple始终是一致的
   浅拷贝外面一层不会变,但是嵌套的列表会改变
   深拷贝只和atuple的原始一样,不会随着atuple的改变而改变

b is (1, 2, 3, [4, 5]), c is (1, 2, 3, [4, 5]), d is (1, 2, 3, [4, 5])
b is (1, 2, 3, [4, 5, 6]), c is (1, 2, 3, [4, 5, 6]), d is (1, 2, 3, [4, 5])

列表:

#!/usr/bin/env/python
# -*-coding:utf-8-*-
# authour:xiapmin_pei

import copy

alist = [1,2,3,[4,5]]

b = alist
c = copy.copy(alist)
d = copy.deepcopy(alist)

print "alist是{0},b是{1},  c是{2},  d是{3}".format(alist,b,c,d)

alist[3].append(6)

print "alist是{0},b是{1},  c是{2},  d是{3}".format(alist,b,c,d)

alist.append(7)

print "alist是{0},b是{1},  c是{2},  d是{3}".format(alist,b,c,d)

结果:可以看出来,将alist赋值给b,b无论怎么变化,都是和alist是一样的
   浅拷贝copy只拷贝第一层,第一层不改变,但是嵌套的列表随着alist的改变而改变
   深拷贝deepcopy只和原先的alist是一致的,无论alist怎么改变,deepcopy只拷贝一次原先的。

alist是[1, 2, 3, [4, 5]],b是[1, 2, 3, [4, 5]], c是[1, 2, 3, [4, 5]], d是[1, 2, 3, [4, 5]]
alist是[1, 2, 3, [4, 5, 6]],b是[1, 2, 3, [4, 5, 6]], c是[1, 2, 3, [4, 5, 6]], d是[1, 2, 3, [4, 5]]
alist是[1, 2, 3, [4, 5, 6], 7],b是[1, 2, 3, [4, 5, 6], 7], c是[1, 2, 3, [4, 5, 6]], d是[1, 2, 3, [4, 5]]