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

Python | deep copy and shallow copy

編輯:Python

 Python Deep copy and shallow copy : This only happens if the container contains a variable data container type

A shallow copy may cause the value after the copy to be modified , Will change the original value

>>> a={"name":"sc","score":[80,90,100]}
>>> b=a.copy()
>>> a
{'name': 'sc', 'score': [80, 90, 100]}
>>> b
{'name': 'sc', 'score': [80, 90, 100]}
>>> b["score"].append(110)
>>> a
{'name': 'sc', 'score': [80, 90, 100, 110]}
>>> b
{'name': 'sc', 'score': [80, 90, 100, 110]}
>>> id(a["score"])
140622729707336
>>> id(b["score"])
140622729707336
>>> id(b)
140622729725560
>>> id(a)
140622729724120

Shallow copy only copies the address of the first layer object ( quote )

Deep copy is to copy the data of each layer ( Use copy Modular deepcopy function )

>>> import copy
>>> b=copy.deepcopy(a) Make a deep copy
>>> a
{'name': 'sc', 'score': [80, 90, 100, 110]}
>>> b
{'name': 'sc', 'score': [80, 90, 100, 110]}
>>> id(a["score"])
140622729707336
>>> id(b["score"])
140622722255816
>>> id(b["name"]) “sc” String resident entered , therefore id identical
140622729721424
>>> id(a["name"])
140622729721424
>>> b["score"].append(120)
>>> b
{'name': 'sc', 'score': [80, 90, 100, 110, 120]}
>>> a
{'name': 'sc', 'score': [80, 90, 100, 110]}


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