list.remove(x) removes objects in more than this list
本问题已经有最佳答案,请猛点这里访问。
当我想要复制我的列表并尝试从一个列表中删除一个项目时,它也会在另一个列表中消失。你能给我一个理由吗?如何只从一个列表中删除?
1 2 3 4 5 6 7 8 9 10 | letter_list = ["A","B","C"] same_letter_list = letter_list print same_letter_list print letter_list same_letter_list.remove("B") print same_letter_list print letter_list |
我的输出是:
1 2 3 4 | ['A', 'B', 'C'] ['A', 'B', 'C'] ['A', 'C'] ['A', 'C'] |
我是编程新手。谢谢你的帮助!
基本上字母表和相同的字母表是相同的地址
1 2 3 4 5 6 7 | >>> letter_list = ["A","B","C"] ... same_letter_list = letter_list ... >>> id(same_letter_list) 1316298424 >>> id(letter_list) 1316298424 |
它会给你一个新地址
1 2 3 | diff_letter_list = letter_list[:] id(diff_letter_list) 1307621296 |
列表是相同的。您可以将它切片到另一个变量,这样它们就不同了。这样地:
1 2 3 4 5 6 7 8 9 10 | letter_list = ["A","B","C"] same_letter_list = letter_list[:] print same_letter_list print letter_list same_letter_list.remove("B") print same_letter_list print letter_list |
因为
如果你想把它们分开,就复印一份
1 | same_letter_list = letter_list.copy() |