python3-- =浅拷贝深拷贝
Posted guang2508
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3-- =浅拷贝深拷贝相关的知识,希望对你有一定的参考价值。
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-- =浅拷贝深拷贝的主要内容,如果未能解决你的问题,请参考以下文章