python copy與deepcopy (拷貝與深拷貝)

來源:互聯網
上載者:User

標籤:印象   list   port   影響   不同   函數   個數   gpo   python   

copy與deepcopy

python 中的copy與deepcopy是記憶體資料的操作,但是兩個函數有一定的區別。

1.copy

import copylist = [1, [4, 5, 6], 2, 3]list1 = copy.copy(list)print id(list)

print id(list[1])print id(list1)print id(list1[1])list[2] = 100list[1][0] = 44print listprint list1結果:46925320469127764696736846912776[1, [44, 5, 6], 100, 3][1, [44, 5, 6], 2, 3]

經過copy操作的得兩個list,list1擁有兩個同的地址(46925320和46967368),修改list時不會影響list1的值,但是 list中間的子列表[4,5,6]在list和list1中有相同的地址46912776,所以在修改list中的子列表會影響到list1中的子列表。

 

2.deepcopy

import copylist = [1, [4, 5, 6], 2, 3]list2 = copy.deepcopy(list)print id(list)print id(list[1])print id(list2)print id(list2[1])list[2] = 100list[1][0] = 44print listprint list2結果:59508232594956885950938459508168[1, [44, 5, 6], 100, 3][1, [4, 5, 6], 2, 3]

經過deepcopy的list與list2用有不用的地址59508232,59509384,其中的子列表頁擁有不同的地址, 所以不論怎樣修改list都不用影響到list2。

結論:

經過copy操作的兩個資料對象擁有不同的得地址空間 ,但是這個資料對象如果是內嵌了其他的複雜資料對象,這個內嵌的資料對象在

兩個資料對象中擁有相同的地址空間,修改其中的值會互相印象。經過deepcopy的操作的不管是內層還是外層資料對象都擁有不同的地址空間,修改其中的值不會對兩個對象都造成影響

python copy與deepcopy (拷貝與深拷貝)

聯繫我們

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