摘要:在 Python 中复制对象可能看起来很简单,但如果不小心,隐藏的陷阱可能会导致严重的错误。在本文中,我们将深入探讨正常复制、浅复制和深复制,并通过您能理解的简单示例进行说明。
在 Python 中复制对象可能看起来很简单,但如果不小心, 隐藏的陷阱可能会导致严重的错误。
在本文中,我们将深入探讨正常复制 、 浅复制和深复制 ,并通过您能理解的简单示例进行说明。
你可以使用以下方式创建浅拷贝:
import copylist1 = [[1, 2], [3, 4]]list2 = copy.copy(list1)list2[0].append(5)print(list1) # Output: [[1, 2, 5], [3, 4]]print(list2) # Output: [[1, 2, 5], [3, 4]]What happened?list2 is a new outer list, but The inner lists ([1,2], [3,4]) are still shared!✅ Key Point: Shallow copy copies the container, but not the contents deeply.import copylist1 = [[1, 2], [3, 4]]list2 = copy.deepcopy(list1)list2[0].append(5)print(list1) # Output: [[1, 2], [3, 4]]print(list2) # Output: [[1, 2, 5], [3, 4]]What happened?list1 stays safe and untouched.list2 is completely separate. ✅ Key Point: Deep copy recursively copies everything inside来源:自由坦荡的湖泊AI一点号