[英]Python list deleting item even though not explicitly told
So I had a very unusual problem with deleting elements from lists, I have recreated the problem in a much smaller and easier to understand format. 因此,从列表中删除元素时遇到了一个非常不寻常的问题,我以更小,更容易理解的格式重新创建了问题。 Basically deleting an item from a list will delete the same item from a different list you have previously set equals to the original list outside of the main loop. 基本上从列表中删除项目将从先前设置的不同列表中删除相同的项目等于主循环之外的原始列表。
a = [1,2,3,4]
b = a
while True:
print("a:", a)
print("b:", b)
c = int(input("delete"))
del(a[c])
print("a:", a)
print("b:", b)
break
This returns: 返回:
a: [1, 2, 3, 4]
b: [1, 2, 3, 4]
delete2 #the "2" is my input
a: [1, 2, 4]
b: [1, 2, 4]
>>>
I researched and saw a few things about shallow/deep copies, but i'm not too sure about that, if anyone could shed some more light that would be great 我研究过并看到了一些关于浅/深拷贝的东西,但是我不太确定,如果有人能够放出一些更好的光
This is because a
and b
are names of the same list (or more formally, references to the same object). 这是因为a
和b
是相同列表的名称(或者更正式地说,是对同一对象的引用)。
To create a name for a new list make a copy of it: 要为新列表创建名称,请复制它:
b = list(a)
# or
b = a[:]
This will create a new list containing the exact same members and is called shallow-copy. 这将创建一个包含完全相同成员的新列表,称为浅拷贝。
A deep-copy is when you recursively copy the entire structure but it seems like its not needed here. 深层复制是当你递归复制整个结构时,但似乎这里不需要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.