二,深浅copy
1,先看赋值运算。
l1 = [1,2,3,[‘barry‘,‘alex‘]] l2 = l1 l1[0] = 111 print(l1) # [111, 2, 3, [‘barry‘, ‘alex‘]] print(l2) # [111, 2, 3, [‘barry‘, ‘alex‘]] l1[3][0] = ‘wusir‘ print(l1) # [111, 2, 3, [‘wusir‘, ‘alex‘]] print(l2) # [111, 2, 3, [‘wusir‘, ‘alex‘]]
对于赋值运算来说,l1与l2指向的是同一个内存地址,所以他们是完全一样的。
2,浅拷贝copy。
l1 = [1,2,3,[‘barry‘,‘alex‘]] l2 = l1.copy() print(l1,id(l1)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2380296895816 print(l2,id(l2)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2380296895048
l1[1] = 222print(l1,id(l1)) # [1, 222, 3, [‘barry‘, ‘alex‘]] 2593038941128print(l2,id(l2)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2593038941896
l1[3][0] = ‘wusir‘ print(l1,id(l1[3])) # [1, 2, 3, [‘wusir‘, ‘alex‘]] 1732315659016 print(l2,id(l2[3])) # [1, 2, 3, [‘wusir‘, ‘alex‘]] 1732315659016
对于浅copy来说,第一层创建的是新的内存地址,而从第二层开始,指向的都是同一个内存地址,所以,对于第二层以及更深的层数来说,保持一致性。
3,深拷贝deepcopy。
import copy l1 = [1,2,3,[‘barry‘,‘alex‘]] l2 = copy.deepcopy(l1) print(l1,id(l1)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2915377167816 print(l2,id(l2)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2915377167048 l1[1] = 222 print(l1,id(l1)) # [1, 222, 3, [‘barry‘, ‘alex‘]] 2915377167816 print(l2,id(l2)) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2915377167048 l1[3][0] = ‘wusir‘ print(l1,id(l1[3])) # [1, 222, 3, [‘wusir‘, ‘alex‘]] 2915377167240 print(l2,id(l2[3])) # [1, 2, 3, [‘barry‘, ‘alex‘]] 2915377167304
对于深copy来说,两个是完全独立的,改变任意一个的任何元素(无论多少层),另一个绝对不改变。
原文地址:https://www.cnblogs.com/zsdbk/p/9387658.html
时间: 2024-11-06 09:54:34