码迷,mamicode.com
首页 > 编程语言 > 详细

python3-- =、浅拷贝、深拷贝

时间:2020-06-15 23:09:41      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:append   赋值   完全   class   port   import   print   bsp   span   

1、赋值 =

# alist = [10,20,[100,200]]
# blist = alist
# blist.append(30)
# print(alist: ,alist, ; id是: ,id(alist))
# print(blist: ,blist, ; id是: ,id(blist))
结果:
alist:  [10, 20, [100, 200], 30]  ; id是:  1722968
blist:  [10, 20, [100, 200], 30]  ; id是:  1722968

结论:alist随着blist变化了

 

2、浅拷贝copy.copy()

import copy
alist = [10,20,[100,200]]
blist = copy.copy(alist)#复制
blist.append(30)
print(alist: ,alist, ; id是: ,id(alist))
print(blist: ,blist, ; id是: ,id(blist))
结果:
alist:  [10, 20, [100, 200]]  ; id是:  9734784
blist:  [10, 20, [100, 200], 30]  ; id是:  9734944
import copy
alist = [10,20,[100,200]]
blist = copy.copy(alist)#复制
blist[-1].append(300)
print(alist: ,alist, ; id是: ,id(alist))
print(blist: ,blist, ; id是: ,id(blist))
结果:
alist:  [10, 20, [100, 200, 300]]  ; id是:  7834320
blist:  [10, 20, [100, 200, 300]]  ; id是:  7833640

结论:copy.copy()中, 父级列表完全独立拷贝,全新地址保存,子级列表是共用的,拷贝不彻底 

 

3、深拷贝 copy.deepcopy()

import copy
alist = [10,20,[100,200]]
blist = copy.deepcopy(alist)
blist.append(30)
blist.append(30)
print(alist: ,alist, ; id是: ,id(alist))
print(blist: ,blist, ; id是: ,id(blist))
结果:
alist:  [10, 20, [100, 200]]  ; id是:  16681640
blist:  [10, 20, [100, 200], 30, 30]  ; id是:  16681000
import copy
alist = [10,20,[100,200]]
blist = copy.deepcopy(alist)
# blist.append(30)
blist[-1].append(300)
blist.append(30)
print(alist: ,alist, ; id是: ,id(alist))
print(blist: ,blist, ; id是: ,id(blist))
结果:
alist:  [10, 20, [100, 200]]  ; id是:  13929208
blist:  [10, 20, [100, 200, 300], 30]  ; id是:  13928568

结论:copy.deepcopy()是彻底的拷贝

python3-- =、浅拷贝、深拷贝

标签:append   赋值   完全   class   port   import   print   bsp   span   

原文地址:https://www.cnblogs.com/guang2508/p/13138253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!