如何在不影响其他列表的情况下使用.remove()?
我想尝试从一个列表中删除一些元素,但不想影响到原来的列表。
这样你可能更容易理解:
>>> list_one = [1,2,3,4]
>>> list_two = list_one
>>> list_two.remove(2)
>>> list_two
[1, 3, 4]
>>> list_one # <- How do I not affect this list?
[1, 3, 4]
有没有什么办法可以解决这个问题呢?
1 个回答
5
你需要让 list_two
成为 list_one
的一个副本,而不是指向它:
>>> list_one = [1,2,3,4]
>>> list_two = list_one[:]
>>> list_two.remove(2)
>>> list_two
[1, 3, 4]
>>> list_one
[1, 2, 3, 4]
>>>
在 list_one
后面加上 [:]
可以创建这个列表的一个浅拷贝。