- 深浅拷贝中首先要判断拷贝元素是不是可变元素
- 可变元素:list dict set(无序) object
- 不可变元素: int float str True Flase None tuple
- 只有一层拷贝
import copy
# 不可变类型 # 可变类型
In [100]: a = 1.0 In [95]: set1 = ([1,2,3])
In [101]: type(a) In [96]: set2 = copy.copy(set1)
Out[101]: float In [98]: set1 == set2
In [102]: b =copy.copy(a) Out[98]: True
In [104]: a == b In [99]: set1 is set2
Out[104]: True Out[99]: False
In [105]: a is b
Out[105]: True
- 浅拷贝:copy.copy()---->两层对象拷贝
- 内层地址相同
- 外层地址
- 如果是可变类型,外层地址不同
- 如果是不可变类型,外层地址相同
In [121]: a = [["a"], [1,2], ["z",23]]
In [122]: type(a)
Out[122]: list
In [123]: b = copy.copy(a)
In [124]: b
Out[124]: [['a'], [1, 2], ['z', 23]]
In [125]: a is b
Out[125]: False
In [126]: a == b
Out[126]: True
In [127]: a[0]==b[0]
Out[127]: True
In [128]: a[0] is b[0]
Out[128]: True
In [129]: a[1] is b[1]
Out[129]: True
In [130]: a[2] is b[2]
Out[130]: True
- 深拷贝:copy.deepcopy()--->两层或者多层对象拷贝
- 如果所有层都是不可变的,所有层地址相同
- 如果所有层都是可变的,所有层地址不同
- 如果内层中,这一层是可变的,地址不同,否者地址相同
- 外层是可变对象--->外层值相等,地址不同
- 外层是不可变对象-->外层值相等,地址根据内层类型,内层中只要有一个可变类型,外层地址就不同
- 外层对象和内层对象只要有一个是可变对象,外层地址就不相同
# 所有层都是可变类型 # 所有层都是不可变类型
In [132]: aa = [["a"], [1,2], ["z",23]] In [142]: aa = (("a"), (1,2), ("z",23))
In [133]: bb = copy.deepcopy(aa) In [143]: bb = copy.deepcopy(aa)
In [134]: bb In [144]: bb
Out[134]: [['a'], [1, 2], ['z', 23]] Out[144]: ('a', (1, 2), ('z', 23))
In [135]: type(aa) In [145]: type(aa)
Out[135]: list Out[145]: tuple
In [136]: aa is bb In [146]: aa is bb
Out[136]: False Out[146]: True
In [137]: aa == bb In [147]: aa[0] is bb[0]
Out[137]: True Out[147]: True
In [138]: aa[0] is bb[0] In [148]: aa[1] is bb[1]
Out[138]: False Out[148]: True
In [139]: aa[1] is bb[1] In [149]: aa[2] is bb[2]
Out[139]: False Out[149]: True
In [140]: aa[2] is bb[2] In [150]: aa == bb
Out[140]: False Out[150]: True
网友评论