我想尝试从列表中删除元素而不影响前一个列表。
这会给你一个更好的画面:
>>> 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]
Run Code Online (Sandbox Code Playgroud)
这个问题有解决方法吗?
小智 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]
>>>
Run Code Online (Sandbox Code Playgroud)
放置[:]在之后list_one会创建列表的浅表副本。