标签: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()是彻底的拷贝
标签:append 赋值 完全 class port import print bsp span
原文地址:https://www.cnblogs.com/guang2508/p/13138253.html