一文掌握如何复制 Python 对象

360影视 动漫周边 2025-05-05 06:07 2

摘要:在 Python 中复制对象可能看起来很简单,但如果不小心,隐藏的陷阱可能会导致严重的错误。在本文中,我们将深入探讨正常复制、浅复制和深复制,并通过您能理解的简单示例进行说明。

在 Python 中复制对象可能看起来很简单,但如果不小心, 隐藏的陷阱可能会导致严重的错误。
在本文中,我们将深入探讨正常复制 浅复制深复制 ,并通过您能理解的简单示例进行说明。

list1 = [1, 2, 3]list2 = list1list2.append(4)print(list1) # Output: [1, 2, 3, 4]print(list2) # Output: [1, 2, 3, 4]Why? Because list1 and list2 are Pointing to the same object in memory.✅ Key Point: Changing list2 also changes list1 because they are linked.

你可以使用以下方式创建浅拷贝:

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一点号

相关推荐