Python的list的内置remove方法,只能删除某个第一次出现:
>>> x = [1, 2, 1, 2, 1, 2]
>>> x.remove(2)
>>> x
[1, 1, 2, 1, 2]
>>>
如果要整体删除list里面的某个元素,可以用列表解析方法(List comprehension):
>>> x = [1, 2, 1, 2, 1, 2]
>>> y = [i for i in x if i != 2] #删除全部2
>>> y
[1, 1, 1]
>>>
同样方法可以用来一次性删除多种元素:
>>> x = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> y = [i for i in x if i != 2 and i != 3] #删除全部2和3
>>> y
[1, 1, 1, 1]
>>>
删除一个范围:
>>> x = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> y = [i for i in x if i < 2] #只保留小于2的
>>> y
[1, 1, 1, 1]
>>>
甚至删除一个集合里的元素:
>>> x = [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> d = [2, 3]
>>> y = [i for i in x if i not in d] #不保留d中的元素
>>> y
[1, 1, 1, 1]
>>>
原文链接:http://www.lfhacks.com/tech/python-remove-all-occurrence