python的几种拷贝方式和区别

  • 浅拷贝 copy
    不拷贝子对象,故如果子对象变化,拷贝的数据子对象也会变化。
  • 深拷贝 deepcopy
    包含对象里面的自对象的拷贝,所以原始对象的改变不会造成深拷贝里任何子元素的改变

看例子:

In [1]: alist = [1,2,[3,4,5],6,7]

In [2]: # 直接赋值,原始对象改变时,拷贝对象也跟随变化

In [3]: blist = alist

In [4]: print alist
[1, 2, [3, 4, 5], 6, 7]

In [5]: print blist
[1, 2, [3, 4, 5], 6, 7]

In [6]: alist[2][1]='a'

In [7]: print alist
[1, 2, [3, 'a', 5], 6, 7]

In [8]: print blist
[1, 2, [3, 'a', 5], 6, 7]

通过浅拷贝,不会拷贝子对象,故子对象若改变,拷贝的对象也会改变

In [10]: import copy

In [11]: clist = copy.copy(alist)

In [12]: print clist
[1, 2, [3, 'a', 5], 6, 7]

In [13]: print alist
[1, 2, [3, 'a', 5], 6, 7]

In [14]: alist.append('b')

In [15]: print alist
[1, 2, [3, 'a', 5], 6, 7, 'b']

In [16]: print blist
[1, 2, [3, 'a', 5], 6, 7, 'b']

In [17]: print clist
[1, 2, [3, 'a', 5], 6, 7]

In [18]: alist[2].append('sub')

In [19]: print alist
[1, 2, [3, 'a', 5, 'sub'], 6, 7, 'b']

In [20]: print clist
[1, 2, [3, 'a', 5, 'sub'], 6, 7]

深拷贝则会完整的拷贝所有原始对象,原始对象的变化不会影响拷贝对像

In [21]: dlist = copy.deepcopy(alist)

In [22]: print dlist
[1, 2, [3, 'a', 5, 'sub'], 6, 7, 'b']

In [23]: print alist
[1, 2, [3, 'a', 5, 'sub'], 6, 7, 'b']

In [24]: alist[2].append(10)

In [25]: print alist
[1, 2, [3, 'a', 5, 'sub', 10], 6, 7, 'b']

In [26]: print dlist
[1, 2, [3, 'a', 5, 'sub'], 6, 7, 'b']

你可能感兴趣的:(python的几种拷贝方式和区别)