[英]Original list still modifies even though copy is made
I have a list currentCell
which contains info like coordinates and values and stuff.我有一个列表currentCell
,其中包含坐标和值等信息。 I then create a copy of that list using currentCellNew = currentCell.copy()
.然后我使用currentCellNew = currentCell.copy()
创建该列表的副本。 Im told that doing that and modifying the copy will NOT effect the original.我告诉我这样做并修改副本不会影响原件。 But when i remove something from the copy, it also removes it from the original list.但是当我从副本中删除某些内容时,它也会从原始列表中删除它。
Here is the code that removes from the copy:这是从副本中删除的代码:
#some variables exist outside of scope
currentCell = next(x for x in self.cells if x[0] == currentCellCoords)
currentCellNew = currentCell.copy()
if currentCellNew[3] == 0:
if **condition**:
wallAxis = next(x[0] for x in list(self.Orientations.items()) if x[1] == "f")
#### Here is the code that removes the element from the copy #####
currentCellNew[2].remove(next(x for x in currentCellNew[2] if x[0] == wallAxis))
list.copy()
is a shallow copy; list.copy()
是浅拷贝; it's fine when the original list
contains immutable objects, but it looks like you've got a list
of list
s, and those inner list
s aren't being copied (the new outer list
has references to the same inner list
s as the first one).当原始list
包含不可变对象时很好,但看起来您有一个list
s 的list
,而那些内部list
s 没有被复制(新的外部list
引用了与第一个相同的内部list
s一)。
You need to use the copy.deepcopy
function to perform the original copy, thereby copying the contents, not just the top-level references:您需要使用copy.deepcopy
函数来执行原始复制,从而复制内容,而不仅仅是顶级引用:
import copy # At top of file
...
currentCellNew = copy.deepcopy(currentCell)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.