b = copy.copy(a)
copy.copy这个函数结果会因为是可变或者不可变导致结果不同
只能拷贝一层。根据类型有关。如果是列表(可变类型),深拷贝。如果是元组(不可变)浅拷贝
如果里面还有嵌套的对象,浅拷贝
import copy
a = [1,2,3,4]
#相当于深拷贝
b = copy.copy(a)
print(id(a))
print(id(b))
a.append(5)
print(a)
print(b)
运行结果:
18904264
18489224
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
import copy
a = (1,2,3,4)
#相当于浅拷贝
b = copy.copy(a)
print(id(a))
print(id(b))
运行结果:
18713160
18713160
import copy
a = [11,22,33]
b = [44,55,66]
c = [a,b]
d = copy.copy(c)
print(id(c))
print(id(d))
print(c)
print(d)
a.append(120)
#c[0].append(120)
print(c)
print(d)
运行结果:
18772104
7561416
[[11, 22, 33], [44, 55, 66]]
[[11, 22, 33], [44, 55, 66]]
[[11, 22, 33, 120], [44, 55, 66]]
[[11, 22, 33, 120], [44, 55, 66]]
import copy
a = [11,22,33]
b = [44,55,66]
c = (a,b)
d = copy.copy(c)
print(id(c))
print(id(d))
print(c)
print(d)
a.append(120)
#c[0].append(120)
print(c)
print(d)
运行结果:
10951368
10951368
([11, 22, 33], [44, 55, 66])
([11, 22, 33], [44, 55, 66])
([11, 22, 33, 120], [44, 55, 66])
([11, 22, 33, 120], [44, 55, 66])