【发布时间】:2021-01-17 06:33:13
【问题描述】:
我对编程比较陌生,而且我一直在理解一些东西,这似乎对于在 Python 中克隆对象非常基础。
假设我们有以下代码,但没有使用 deepcopy 模块:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
copy = [x for x in nested_list]
现在如果我们这样做:
copy[1] = [9999999]
然后它将返回以下内容:
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
copy = [[1, 2, 3], [9999999], [7, 8, 9]]
但是,如果我们只修改其中一个嵌套列表中的单个元素,例如:
copy[0][1] = 9999999
那么原始变量和复制变量都会返回相同的值:
nested_list = [[1, 9999999, 3], [4, 5, 6], [7, 8, 9]]
copy = [[1, 9999999, 3], [4, 5, 6], [7, 8, 9]]
为什么当我们给嵌套列表一个新值时它工作得很好,但是当我们给嵌套列表中的一个项目一个新值时,它也会改变原来的值?对变量 nested_list 和 copy 调用 id() 函数表明它们是独立的对象,至少在我的理解中是这样。
例如:
copy = nested_list # copy and nested_list share the same id()
copy = [x for x in nested_list] # now they have different id()
copy = deepcopy(nested_list) # again they have different id()
我知道另一种解决方案是 deepcopy 功能,但是由于它非常慢,我想知道是否有其他解决方案?
提前感谢大家!
【问题讨论】:
-
这不是python的一个有趣的功能吗...?我仍然有问题,甚至无法完全解释。
-
@goalie1998。不仅仅是蟒蛇。任何使用指针的语言,不管你怎么称呼它们。
标签: python logic python-module deep-copy