python基础,深浅拷贝
赋值
1 直接赋值(字典同理)
lst1 = [1,2,3]lst2 = [1,2,3]print(id(lst1),id(lst2))
2 引用赋值(字典同理)结果:
2426068165192 2426069393800
lst2 = [1,2,3]lst3 = lst2print(id(lst2),id(lst3))lst3.append(4)print(lst2)print(lst3)
结果:
1857178919496 1857178919496
[1, 2, 3, 4]
[1, 2, 3, 4]
浅拷贝
1 一维列表
lst2 = [1,2,3]lst3 = lst2.copy() #写法1# lst3 = lst2.[:] #写法2print(id(lst2),id(lst3))lst3.append(4)lst2.append(5)print(lst2)print(lst3)
2 多维列表,子列表为引用赋值(字典同理)结果:
2119837508168 2119838736776
[1, 2, 3, 5]
[1, 2, 3, 4]
lst1 = [1,2,3,['a','b','c']]lst2 = lst1[:]print('1维列表内存地址',id(lst1),id(lst2))lst1[3].append('dd')lst2[3].append('hhh')print('2维列表内存地址',id(lst1[3]),id(lst2[3]))print(lst1)print(lst2)
深拷贝1 引入拷贝模块结果:
1维列表内存地址 2362867982664 2362868023752
2维列表内存地址 2362838377032 2362838377032
[1, 2, 3, ['a', 'b', 'c', 'dd', 'hhh']]
[1, 2, 3, ['a', 'b', 'c', 'dd', 'hhh']]
import copy #引入拷贝模块lst1 = [1,2,3,['a','b','c']]lst2 = copy.deepcopy(lst1)print('1维列表内存地址',id(lst1),id(lst2))lst1[3].append('dd')lst2[3].append('hhh')print('2维列表内存地址',id(lst1[3]),id(lst2[3]))print(lst1)print(lst2)
结果:
1维列表内存地址 2734949178056 2734949176840
2维列表内存地址 2734949267080 2734949267400
[1, 2, 3, ['a', 'b', 'c', 'dd']]
[1, 2, 3, ['a', 'b', 'c', 'hhh']]
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。