导入 copya = \'deepak\'b = 1, 2, 3, 4c = [1, 2, 3, 4]d = {1: 10, 2: 20, 3: 30}a1 = copy.copy(a)b1 = copy.copy(b)c1 = copy.copy(c)d1 = copy.copy(d) print(\'immutable - id(a)==id(a1)\', id(a...
import copy
a = "deepak"
b = 1, 2, 3, 4
c = [1, 2, 3, 4]
d = {1: 10, 2: 20, 3: 30}
a1 = copy.copy(a)
b1 = copy.copy(b)
c1 = copy.copy(c)
d1 = copy.copy(d)
print("immutable - id(a)==id(a1)", id(a) == id(a1))
print("immutable - id(b)==id(b1)", id(b) == id(b1))
print("mutable - id(c)==id(c1)", id(c) == id(c1))
print("mutable - id(d)==id(d1)", id(d) == id(d1))
我得到以下结果:
immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False
如果我执行深度复制:
a1 = copy.deepcopy(a)
b1 = copy.deepcopy(b)
c1 = copy.deepcopy(c)
d1 = copy.deepcopy(d)
结果是一样的:
immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) False
mutable - id(d)==id(d1) False
如果我进行赋值操作:
a1 = a
b1 = b
c1 = c
d1 = d
结果是:
immutable - id(a)==id(a1) True
immutable - id(b)==id(b1) True
mutable - id(c)==id(c1) True
mutable - id(d)==id(d1) True
有人能解释一下这些副本之间到底有什么区别吗?这和可变和不可变对象有关吗?如果是的话,你能给我解释一下吗?
深层复制与嵌套结构相关。如果您有列表列表,则深层复制也会复制嵌套列表,因此它是递归复制。仅使用复制,您就会有一个新的外部列表,但内部列表是引用。赋值不会复制。例如
import copy
spam = [[0, 1, 2, 3], 4, 5]
cheese = copy.copy(spam)
cheese.append(3)
cheese[0].append(3)
print(spam)
print(cheese)
输出
[[0, 1, 2, 3, 3], 4, 5][[0, 1, 2, 3, 3], 4, 5, 3]复制方法将外部列表的内容复制到新列表,但内部列表对于两个列表仍然相同,因此如果您对任何列表的内部列表进行更改,它将影响两个列表。
但是如果使用深度复制,那么它也会为内部列表创建新的实例。
import copy
spam = [[0, 1, 2, 3], 4, 5]
cheese = copy.deepcopy(spam)
cheese.append(3)
cheese[0].append(3)
print(spam)
print(cheese)
输出
[0, 1, 2, 3][[0, 1, 2, 3, 3], 4, 5, 3]