Python从零开始 day7

深浅拷贝

# 深浅拷贝
a = [[1,2],3,4]
b = a # 深拷贝,a和b的id一致 ,共享一个地址 a变b也变 ,除了int str外 b=a都是共享一个内存地址
# print(a,b)
b[0] = 'fishy'
print(a,b) # ['fishy', 3, 4] ; ['fishy', 3, 4]

a = [[1,2],3,4]
b1 = a.copy() # 浅拷贝 只能复制第一层(即在新复制的对象b1中新建内存地址),第二层不会被复制和a共享内存地址
print(b1) # [[1, 2], 3, 4]
b1[0] = 'fishy' # 重新在内存中新建一个ID
print(a) # [[1, 2], 3, 4]
print(b1) # ['fishy', 3, 4]
a[2] = 5
print(a) # [[1, 2], 3, 5]
print(b1) # [[1, 2], 3, 4]

import copy
a = ['fishy',25,['game',10,20]]
b = copy.copy(a) # shallow copy 浅拷贝
# print(a,id(a[2])) # ['fishy', 25, ['game', 10, 20]] 2745783050760
# print(b,id(b[2])) # ['fishy', 25, ['game', 10, 20]] 2745783050760 内存地址一致

c = copy.deepcopy(a) # 深拷贝 完全复制一份
print(c,id(c[2])) # 内存地址不一致
print(a,id(a[2]))
c[0] = 'yubang'
print(a) # ['fishy', 25, ['game', 10, 20]]
print(c) # ['yubang', 25, ['game', 10, 20]]
c[2][1] = 30
print(a) # ['fishy', 25, ['game', 10, 20]]
print(c) # ['fishy', 25, ['game', 30, 20]]

转载于:https://www.cnblogs.com/yubang178/p/10269473.html

你可能感兴趣的:(Python从零开始 day7)