Python从list1中删除列表值x,如下面的代码所示:
list1 = ['a', 'b', 'c', 'c', 'a', 'x']
list2 = list1
#Remove value 'x' from list2
list2.remove('x')
#print list1
list1
['a', 'b', 'c', 'c', 'a']
答案 0 :(得分:1)
`list2 = list1` it is not a copy. list2 has only references to list1.
Use `deepcopy`, if the list to copy contains compound objects,
or use list2 = list(list1) for non compound objects.
# use deep copy if the list contains compound objects
from copy import deepcopy
list2 = deepcopy(list1)
list1 = ['a', 'b', 'c', 'c', 'a', 'x']
list2 = list1
list2 = deepcopy(list1)
list2.remove('x')
print(list1)
['a', 'b', 'c', 'c', 'a', 'x']