1.应用copy库:
1 import copy 2 3 #当 变量 = xxxx 时 可以理解为变量指向xxxx所在的地址 4 a = [11,22] 5 b = [33,44] 6 c = [a,b] 7 x = (a,b) 8 9 d = c # d 和 c 同时指向 10 print("---指向---") 11 print(id(c)) # 3037957585544 12 print(id(d)) # 3037957585544 13 14 # 浅拷贝 只拷贝最外层的数据 内部指向地址不变 但是 如果拷贝的对象是元祖 无论元祖里面的值是否可变 都是引用 而不拷贝 即id()结果相同 15 e = copy.copy(c) 16 print("---浅拷贝1---") 17 print(id(c)) # 3037957585544 18 print(id(e)) # 3037957181064 19 print(id(c[0])) # 3037957586248 20 print(id(e[0])) # 3037957586248 21 22 # 浅拷贝遇元祖 变指向 23 e2 = copy.copy(x) 24 print("---浅拷贝遇元祖---") 25 print(id(x)) # 3037957178696 26 print(id(e2)) # 3037957178696 27 print(id(x[0])) # 3037957586248 28 print(id(e2[0])) # 3037957586248 29 30 # 深拷贝 把数据完全拷贝出来放在新地址 包括内部指向地址的值 31 f = copy.deepcopy(c) 32 print("---深拷贝---") 33 print(id(c)) # 3037957585544 34 print(id(f)) # 3037957586312 35 print(id(c[0])) # 3037957586248 36 print(id(f[0])) # 3037957586888 37 38 # 深拷贝遇元祖1:如果元祖里面的值是可变的 则依然是深拷贝 递归全拷 39 f2 = copy.deepcopy(x) 40 print("---深拷贝遇元祖1---") 41 print(id(x)) # 3037957178696 42 print(id(f2)) # 3037926301768 43 print(id(x[0])) # 3037957586248 44 print(id(f2[0])) # 3037957586504 45 # 深拷贝遇元祖2:如果元祖里面的值都是不可变 则变指向 46 a3 = (11,22) 47 b3 = (33,44) 48 c3 = (a3,b3) 49 f3 = copy.deepcopy(c3) 50 print("---深拷贝遇元祖2---") 51 print(id(c3)) # 3037957178824 52 print(id(f3)) # 3037957178824 53 print(id(c3[0])) # 3037957179592 54 print(id(f3[0])) # 3037957179592
2.切片是浅拷贝:
1 a = [11,22] 2 b = [33,44] 3 c = [a,b] 4 d = c[:] 5 print("---切片---") 6 print(id(c)) # 2801867735752 7 print(id(d)) # 2801867735624 8 print(id(c[0])) # 2801867705608 9 print(id(d[0])) # 2801867705608
3.字典的copy()方法是浅拷贝:
1 d = dict(name="zhangsan",age=27,children_age=[11, 22]) 2 e = d.copy() 3 d["children_age"].append(9) 4 print(d) # {'name': 'zhangsan', 'children_age': [11, 22, 9], 'age': 27} 5 print(e) # {'name': 'zhangsan', 'age': 27, 'children_age': [11, 22, 9]}