简体   繁体   English

Python列表删除项目,即使没有明确告诉

[英]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). 这是因为ab是相同列表的名称(或者更正式地说,是对同一对象的引用)。

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.

相关问题 Python:即使列表中的项目存在,如果列表中的项目仍为False - Python: if item in list evaluates False even though the item exists 克隆列表似乎起着别名的作用,即使已明确声明为一个克隆 - Cloned list seems to be functioning as an alias, even though explicitly declared as a a clone 即使显式导入 Python 名称“os”也未定义 - Python name 'os' is not defined even though it is explicitly imported Python:即使它肯定存在,也不会在列表中找到字符串 - Python: will not find a string in a list even though it definitely is there 从列表中删除列表项后的行为 <item> 在python中 - Behaviour after deleting list item from List<item> in python PYTHON 获取列表的最后一项,即使它为空 - PYTHON get the last item of a list even if empty 即使元素在Python列表中也存在值错误 - Value error even though element is present inside the list in Python .pop()似乎在Python中触发TypeError,即使结果应该是一个列表 - .pop() seems to be triggering a TypeError in Python, even though the result should be a list 即使打印功能正在打印列表,Python中也会读取文件错误 - Read file error in Python, even though print function is printing the list Python:即使存在列表元素也无法访问 - Python : Cannot access list element even though it exists
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM