python中的深拷貝和潛拷貝

來源:互聯網
上載者:User

標籤:

>>> a = [‘ace‘,[‘age‘,10]]>>> b = a[:]>>> c = list(a)>>> for item in a:...     print(id(item))...     140281621219736140281621134800>>> for item in b:    print(id(item))...     140281621219736140281621134800>>> for item in c:    print(id(item))...     140281621219736140281621134800

 看得出,這裡的集中拷貝方式都只是類似指標的引用。。改改試試?

>>> b[0] = ‘bog‘>>> b[‘bog‘, [‘age‘, 10]]>>> a[‘ace‘, [‘age‘, 10]]>>> c[‘ace‘, [‘age‘, 10]]>>> c[0] = ‘cat‘>>> a[‘ace‘, [‘age‘, 10]]>>> b[‘bog‘, [‘age‘, 10]]>>> c[‘cat‘, [‘age‘, 10]]

 艾,變了。在改改列表?

>>> a[‘ace‘, [‘age‘, 10]]>>> b[‘bog‘, [‘age‘, 10]]>>> c[‘cat‘, [‘age‘, 10]]>>> a[1][1] = ‘ago‘>>> a[‘ace‘, [‘age‘, ‘ago‘]]>>> b[‘bog‘, [‘age‘, ‘ago‘]]>>> c[‘cat‘, [‘age‘, ‘ago‘]]>>> b[1][1] = ‘agy‘>>> a[‘ace‘, [‘age‘, ‘agy‘]]>>> b[‘bog‘, [‘age‘, ‘agy‘]]>>> c[‘cat‘, [‘age‘, ‘agy‘]]>>> c[1][1] = ‘cat!‘>>> a[‘ace‘, [‘age‘, ‘cat!‘]]>>> b[‘bog‘, [‘age‘, ‘cat!‘]]>>> c[‘cat‘, [‘age‘, ‘cat!‘]]

 艾瑪,全變了。。。什麼情況阿!

哈哈,來個總結!

發現,其中列表中  姓名字串  id都不一樣,但是 年齡列表id卻都相同。

這是因為:python中字串不可以修改,所以在為tom和anny重新命名的時候,會重新建立一個’tom’和’anny’對象,替換舊的’jack’對象。

這就說明了,淺複製(shallow copy),它複製了對象,但對於對象中的元素,依然使用引用.

 

那深拷貝也就是玩玩全全的從記憶體空間新開闢一個地址存一個副本辣!

怎麼用呢?

 

>>> import copy>>> d = copy.deepcopy(a)>>> for item in a:...     print(id(a))...     140281621133432140281621133432>>> for item in d:    print(id(item))...     140281621219736140281621159160

 

 see!不一樣了把

 

python中的深拷貝和潛拷貝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.