先来看看复制运算

复制运算列表和复制的目标列表指向的是一个内存地址,一改变就都改变了.

 

浅copy                                                                                                                          深copy

1.原理                                   1.原理

让列表与复制的目标列表指向同一个内存,来复制列表.              让列表与目标列表指向不同内存来复制列表.

2.公式                                  2.公式

[要复制的列表].copy()                            copy.deepcopy(要复制的目标列表)

3.性质                                  3.性质

第一层指向内存相同,第二层指向内存相同                   不管有几层指向内存均不同.

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] = 222
print(l1,id(l1))  # [1, 222, 3, ['barry', 'alex']] 2593038941128
print(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']]
View Code
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']]
View Code
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
View Code

 

posted on 2018-01-29 15:46  仓鼠大人爱吃肉  阅读(155)  评论(0编辑  收藏  举报