赋值拷贝,浅拷贝与深拷贝

赋值拷贝,浅拷贝与深拷贝

赋值拷贝 [引用拷贝]

特点:拷贝出来的新的列表与原本列表,他们两个共用同一块内存,
若列表发生变化,则同时进行改变.

list1 = [1,2,3,4,[1,2,3]]
list2 = list1

print(list1)     # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list2)     # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(id(list1))  # 输出结果 2329447376520
print(id(list2))  # 输出结果 2329447376520

list2[-1][-1] = 1
print(list2)     # 输出结果 [1, 2, 3, 4, [1, 2, 1]]
print(list1)     # 输出结果 [1, 2, 3, 4, [1, 2, 1]]
print(id(list1))  # 输出结果 2329447376520
print(id(list2))  # 输出结果 2329447376520

list2[-1] = "hello"
print(list2)    # 输出结果 [1, 2, 3, 4, 'hello']
print(list1)    # 输出结果 [1, 2, 3, 4, 'hello']
print(id(list1))  # 输出结果 2329447376520
print(id(list2))  # 输出结果 2329447376520


浅拷贝

特点:对于一维列表,会开辟新的内存空间,拷贝出来的新的列表与原本的列表id并不相同,
但是这仅限于一维列表.这种拷贝方式是一种不完全拷贝.
若出现二维列表,有可能仍然会出现共用内存的情况.

import copy
list1 = [1,2,3,4,[1,2,3]]
list3 = list1.copy()

print(list1)  # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list3)  # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(id(list1))  # 输出结果 1975663482504
print(id(list3))  # 输出结果 1975663504008



list3[0] = 2
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list3) # 输出结果 [2, 2, 3, 4, [1, 2, 3]]
print(id(list1))  # 输出结果 1975663482504
print(id(list3))  # 输出结果 1975663504008



list3[-1][-1] = "good"
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 'good']]
print(list3) # 输出结果 [2, 2, 3, 4, [1, 2, 'good']]
print(id(list1))  # 输出结果 1975663482504
print(id(list3))  # 输出结果 1975663504008
深拷贝

特点:是一种完全拷贝,它重新递归开辟一块新的内存空间,若出现多维列表的情况下,
多维列表的内存也会重新复制一份.新的列表与原列表不会出现共用内存的情况.

import copy
list1 = [1,2,3,4,[1,2,3]]
list4 = copy.deepcopy(list1)

print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list4) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(id(list1)) # 输出结果 1968912750216
print(id(list4)) # 输出结果 1968912771720


list4[0] = 5
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list4) # 输出结果 [5, 2, 3, 4, [1, 2, 3]]
print(id(list1)) # 输出结果 1968912750216
print(id(list4)) # 输出结果 1968912771720


list4[-1][-1] = "nice"
print(list1) # 输出结果 [1, 2, 3, 4, [1, 2, 3]]
print(list4) # 输出结果 [5, 2, 3, 4, [1, 2, 'nice']]
print(id(list1)) # 输出结果 1968912750216
print(id(list4)) # 输出结果 1968912771720
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值