1 import copy 2 3 字典参照列表结论,看是否有深层嵌套。 4 a = {'name':1,'age':2} 5 b = a 6 a['name'] = 'ff' 7 print(a) 8 print(b) 9 print(id(a),id(b)) 10 11 12 a = {'name':1,'age':2} 13 b = copy.deepcopy(a) 14 a['name'] = 'ff' 15 print(a) 16 print(b) 17 print(id(a),id(b)) 18 """ 19 {'name': 'ff', 'age': 2} 20 {'name': 'ff', 'age': 2} 21 4301093048 4301093048 22 {'name': 'ff', 'age': 2} 23 {'name': 1, 'age': 2} 24 4301093120 4302783256 25 """ 26 27 字符串和元组等不可变数据类型,打死都不变 28 a = 'ff' 29 b = a 30 a = 'ff1' 31 print(a,b) # ff1 ff 32 33 a = 'ff' 34 b = copy.copy(a) 35 a = 'ff1' 36 print(a,b) # ff1 ff 37 38 a = 'ff' 39 b = copy.deepcopy(a) 40 a = 'ff1' 41 print(a,b) # ff1 ff 42 43 a = [1,2,3] 44 b = [4,5,6] 45 c = [a,b] 46 d = c 47 print(id(c),id(d)) # 4322641352 4322641352 48 c.append(9) 49 print(c) # [[1, 2, 3], [4, 5, 6], 9] 50 print(d) # [[1, 2, 3], [4, 5, 6], 9] 51 print(id(c),id(d)) # 4322641352 4322641352 52 53 d = copy.copy(c) 54 c.append(9) 55 print(c) # [[1, 2, 3], [4, 5, 6], 9] 56 print(d) # [[1, 2, 3], [4, 5, 6]] 57 c[0].append(8) 58 print(c) # [[1, 2, 3, 8], [4, 5, 6]] 59 print(d) # [[1, 2, 3, 8], [4, 5, 6]] 60 如果只是copy的话,copy.copy() 针对外层依旧是深拷贝,但对内层来讲就是浅拷贝了,会改变值。 61 62 63 d = copy.deepcopy(c) 64 c.append(9) 65 print(c) # [[1, 2, 3], [4, 5, 6], 9] 66 print(d) # [[1, 2, 3], [4, 5, 6]] 67 c[0].append(8) 68 print(c) # [[1, 2, 3, 8], [4, 5, 6]] 69 print(d) # [[1, 2, 3], [4, 5, 6]] 70 深拷贝, 不管你是啥,只要copy.deepcopy()了。 不管你变不变,我变我是狗。