人生苦短,我用python。
一、拷贝
1、is、==
1 2 3 4 5 6 7 8 9 10 11
|
a = [1,2,3] b = a c = [1,2,3]
print(a is b) print(a == b) print(a is c) print(a == c)
|
2、赋值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
import copy
a = 1 b = a print(id(a)) print(id(b)) a=2 print(a) print(b)
a = [11, 22, 33] b = a print(id(a)) print(id(b)) a.append(44) print(a) print(b)
|
3、浅拷贝
原子对象(数字、字符串)其实没有拷贝,产生的都是对原对象的引用。
组合对象(列表、字典、集合、元组)才有浅拷贝和深拷贝。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
import copy
a = (11,22,33) b = copy.copy(a) print(id(a)) print(id(b))
a = [11,22,33] b = copy.copy(a) print(id(a)) print(id(b)) a.append(44) print(a) print(b)
a = (11,22,33) b = [1,2,3] c = (a,b) e = copy.copy(c) print(id(c)) print(id(e)) b.append(4) print(c) print(e)
|
4、深拷贝
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
import copy
a = (11,22,33) b = copy.deepcopy(a) print(id(a)) print(id(b))
a = [11,22,33] b = copy.deepcopy(a) print(id(a)) print(id(b)) a.append(44) print(a) print(b)
a = (11,22,33) b = [1,2,3] c = (a,b) e = copy.deepcopy(c) print(id(c)) print(id(e)) b.append(4) print(c) print(e)
|
持续更新…