程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Understanding Python concept -- deep and shallow copy

編輯:Python

1、 shallow copy :List1 and List2 In essence, the referenced memory addresses are consistent , Modify a character symbol , The new address will be updated , therefore List1 and List2 Will not synchronize changes ;

Nested list modification will update synchronously , In essence, this nested list address has not been modified , therefore List2 After modifying the characters in the nested list in , The list address is unchanged , therefore List1 The nested list of still refers to the same address

List1 = ['List1',['A', 'B']]
List2 = List1.copy()
print(List1,List2,id(List1[0]) ,id(List2[0]))
List2[0]='List2 modify '
print(List1,List2,id(List1[0]) ,id(List2[0]))
List2[-1][0] = 'A Switch to B'
print(List1,List2,id(List1[0]) ,id(List2[0]))
Return results :
['List1', ['A', 'B']] ['List1', ['A', 'B']] 2833940373664 2833940373664
['List1', ['A', 'B']] ['List2 modify ', ['A', 'B']] 2833940373664 2833941158384
['List1', ['A Switch to B', 'B']] ['List2 modify ', ['A Switch to B', 'B']] 2833940373664 2833941158384

2、 deep copy The new address is used , So the changes will not affect each other .

import copy
List1 = ['List1',['A', 'B']]
List2 = copy.deepcopy(List1)
print(List1,List2,id(List1[0]) ,id(List2[0]))
List2[0]='List2 modify '
print(List1,List2,id(List1[0]) ,id(List2[0]))
List2[-1][0] = 'A Switch to B'
print(List1,List2,id(List1[0]) ,id(List2[0]))
Return results :
['List1', ['A', 'B']] ['List1', ['A', 'B']] 1990707863712 1990707863712
['List1', ['A', 'B']] ['List2 modify ', ['A', 'B']] 1990707863712 1990708779504
['List1', ['A', 'B']] ['List2 modify ', ['A Switch to B', 'B']] 1990707863712 1990708779504


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved