python:更改列表的副本会更改原始副本吗? [英] python: mutating the copy of a list changes the original?

查看:117
本文介绍了python:更改列表的副本会更改原始副本吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以直到现在,我仍然假设,例如,如果您有:

So until now, i was under the assumption that if you have for example:

L = [1,2,3]
L2 = L1
L2.append(5)

L和L2都将受到附加代码的影响.

both L and L2 would be affected by the append code.

但是,当您将L2分配为列表的副本时,例如:

however, when you assign L2 to be a copy of a list, for example:

L = [1,2,3]
L2 = L[:]
L2.append(5)

只有L2会受到影响,而L仍指[1,2,3]

only L2 would be affected, and L still refers to [1,2,3]

但我现在遇到了这个问题:

but i now run into this:

x = [1, 2]
L1 = [x, [8, 9]]
L2 = L1[:]
L2[0][1] = 999

>>>print(L1)
[[1,999],[8,9]]
>>>print(L2)
[[1,999],[8,9]]

为什么在这种情况下两个列表都改变了?

why was it that in this case, both lists changed?

推荐答案

切片是浅表副本.通过切片创建的副本将包含对原始列表中旧元素的新引用;如果原始列表包含可变对象(例如更多列表),则副本将包含对这些相同列表的引用.您可以使用copy.deepcopy尝试解决此问题,或者循环浏览原始列表并将这些元素切片复制到新列表中.但是,请注意copy.deepcopy;您经常需要停止复制并保留原始元素.

Slicing is a shallow copy. A copy created by slicing will contain new references to the old elements of the original list; if the original list contained mutable objects such as more lists, the copy will contain references to those same lists. You can use copy.deepcopy to try to get around this, or loop through your original list and slice-copy the elements into a new list. Be careful with copy.deepcopy, though; there's often some depth at which you want to stop making copies and keep the original elements.

这篇关于python:更改列表的副本会更改原始副本吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆