python3之深淺copy對比

來源:互聯網
上載者:User

標籤:int   地址空間   pen   記憶體位址   back   ack   pre   12px   一致性   

一、賦值對比

1、列表

l1 = [1,2,3]l2 = l1l1.append('a')print(l1,l2)               #[1, 2, 3, 'a'] [1, 2, 3, 'a']print(id(l1),id(l2))          #43499848 43499848#可以看到兩個列表的值以及id值相同,對應的是同一個記憶體位址

2、字典

dic = {'name':'barry'}dic1 = dicdic['age'] = 18print(dic,dic1)            #{'name': 'barry', 'age': 18} {'name': 'barry', 'age': 18}print(id(dic),id(dic1))       #31157344 31157344#可以看到兩個字典的值以及id值相同,對應的是同一個記憶體位址


3、字串

s = 'alex's1 = ss2 = s.replace('a','A')print(s,s1,s2)                  #alex alex Alexprint(id(s),id(s1),id(s2))           #31040208 31040208 31040376#賦值是同一個記憶體位址,替換字串後的變數s2是另外的地址


二、深淺copy

1、淺copy

對於淺copy來說,第一層建立的是新的記憶體位址。而從第二層開始,指向的是同一個記憶體位址,所有,對於第二層以及更深的層數來說,保持一致性。

# 1、普通淺copy

l1 = [1,2,3,4]l2 = l1.copy()l1.append('a')print(l1,l2)                     #[1, 2, 3, 4, 'a'] [1, 2, 3, 4]print(id(l1),id(l2))             #37077320 37078664#id記憶體位址不一樣,建立了兩個地址空間,一個改變,另一個不會變化

# 2、嵌套淺copy


l1 = [1,[22,33,44],3,4,]l2 = l1.copy()l1[1].append('a')print(l1,id(l1),l2,id(l2))       #[1, [22, 33, 44, 'a'], 3, 4]  [1, [22, 33, 44, 'a'], 3, 4]print(id(l1),id(l2))              #43173512 43173256print(id(l1[1]),id(l2[1]))       #43172168 43172168# 第一層都是獨立的的。從第二層開始都是是公用的,改一個都會變。l1 = [1,[22,33,44],3,4,]l2 = l1.copy()l1[0] = 111print(l1,l2)                     #[111, [22, 33, 44], 3, 4] [1, [22, 33, 44], 3, 4]print(id(l1),id(l2))             #43370120 43369864# 可以看到第一層都是獨立的,改一個不影響另一個的結果

2、 深copy.deepcopy()

對於深copy來說,兩個是完全獨立的,改變任意一個的元素(無論是多少層),另一個絕不會改變。


import copyl1 = [1,[22,33,44],3,4,]l2 = copy.deepcopy(l1)# 改變第一層l1[0] = 111print(l1,l2)                    #[111, [22, 33, 44], 3, 4] [1, [22, 33, 44], 3, 4]print(id(l1),id(l2))            #43238536 43239048# 改變第二層l1[1].append('a')print(l1,l2)                   # [111, [22, 33, 44, 'a'], 3, 4] [1, [22, 33, 44], 3, 4]print(id(l1),id(l2))           #43238536 43239048



python3之深淺copy對比

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.