开发者

How can I remove all instances of an element from a list in Python? [duplicate]

开发者 https://www.devze.com 2022-12-19 12:00 出处:网络
This question already has answers here: 开发者_如何学JAVA Remove all occurrences of a value from a list?
This question already has answers here: 开发者_如何学JAVA Remove all occurrences of a value from a list? (25 answers) Closed 7 years ago.

Lets say I have a list a:

a = [[1, 1], [2, 2], [1, 1], [3, 3], [1, 1]]

Is there a function that removes all instances of [1, 1]?


If you want to modify the list in-place,

a[:] = [x for x in a if x != [1, 1]]


Use a list comprehension:

[x for x in a if x != [1, 1]]


Google finds Delete all items in the list, which includes gems such as

from functools import partial
from operator import ne
a = filter(partial(ne, [1, 1]), a)


def remAll(L, item):
    answer = []
    for i in L:
        if i!=item:
            answer.append(i)
    return answer


Here is an easier alternative to Alex Martelli's answer:

a = [x for x in a if x != [1,1]]


new_list = filter(lambda x: x != [1,1], a)

Or as a function:

def remove_all(element, list):
    return filter(lambda x: x != element, list)

a = remove_all([1,1],a)

Or more general:

def remove_all(elements, list):
    return filter(lambda x: x not in elements, list)

a = remove_all(([1,1],),a)


filter([1,1].__ne__,a)


pure python no modules version, or no list comp version ( simpler to understand ?)

>>> x = [1, 1, 1, 1, 1, 1, 2, 3, 2]
>>> for item in xrange(x.count(1)):
...     x.remove(1)
...
>>>
>>> x
[2, 3, 2]

can be made into a def pretty easily also

def removeThis(li,this):
    for item in xrange(li.count(this)):
           li.remove(this)
    return li
0

精彩评论

暂无评论...
验证码 换一张
取 消