首页 > 代码库 > python中对列表浅复制深复制另类的理解方式
python中对列表浅复制深复制另类的理解方式
‘‘‘
创建者:徐洋
创建时间:2017年6月13日22:25:23
代码功能:详细分析列表的浅copy和深度copy
‘‘‘
#导入copy模块
import copy
list1 = [1,2,3,["a","b","c"]]
#对表1进行浅复制
list2 = copy.deepcopy(list1)#copy.copy
#查询表1中各个元素的内存地址
address0 = id(list1[0])
address1 = id(list1[1])
address2 = id(list1[2])
address3 = id(list1[3])
address30 = id(list1[3][0])
address31 = id(list1[3][1])
address32 = id(list1[3][2])
#查询表2中各个元素的内存地址
address_0 = id(list2[0])
address_1 = id(list2[1])
address_2 = id(list2[2])
address_3 = id(list2[3])
address_30 = id(list2[3][0])
address_31 = id(list2[3][1])
address_32 = id(list2[3][2])
# 打印出列表1的内存地址和列表2的内存地址
print("---------第一次比较---------")
print("列表1:",address0,address1,address2,address3,address30,address31,address32)
print("列表2:",address_0,address_1,address_2,address_3,address_30,address_31,address_32)
# 修改列表1中某个值
list1[1]=-1
#查询表1中各个元素的内存地址
address0 = id(list1[0])
address1 = id(list1[1])
address2 = id(list1[2])
address3 = id(list1[3])
address30 = id(list1[3][0])
address31 = id(list1[3][1])
address32 = id(list1[3][2])
#查询表2中各个元素的内存地址
address_0 = id(list2[0])
address_1 = id(list2[1])
address_2 = id(list2[2])
address_3 = id(list2[3])
address_30 = id(list2[3][0])
address_31 = id(list2[3][1])
address_32 = id(list2[3][2])
# 打印此时列表1的内存地址和列表2的内存地址
print("---------第二次比较---------")
print("列表1:",address0,address1,address2,address3,address30,address31,address32)
print("列表2:",address_0,address_1,address_2,address_3,address_30,address_31,address_32)
print(list1,list2)
# 修改列表1中第三个元素中的值
list1[3][1] = 6
#查询表1中各个元素的内存地址
address0 = id(list1[0])
address1 = id(list1[1])
address2 = id(list1[2])
address3 = id(list1[3])
address30 = id(list1[3][0])
address31 = id(list1[3][1])
address32 = id(list1[3][2])
#查询表2中各个元素的内存地址
address_0 = id(list2[0])
address_1 = id(list2[1])
address_2 = id(list2[2])
address_3 = id(list2[3])
address_30 = id(list2[3][0])
address_31 = id(list2[3][1])
address_32 = id(list2[3][2])
# 打印此时列表1的内存地址和列表2的内存地址
print("---------第三次比较---------")
print("列表1:",address0,address1,address2,address3,address30,address31,address32)
print("列表2:",address_0,address_1,address_2,address_3,address_30,address_31,address_32)
# 原因分析:看图
print(list1,list2)
python中对列表浅复制深复制另类的理解方式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。