我想从列表中删除一个值,如果它存在于列表中(它可能不存在)。

a = [1, 2, 3, 4]
b = a.index(6)

del a[b]
print(a)

上面给出了错误:

ValueError: list.index(x): x not in list

所以我必须这样做:

a = [1, 2, 3, 4]

try:
    b = a.index(6)
    del a[b]
except:
    pass

print(a)

难道没有更简单的方法吗?


当前回答

要删除一个元素的第一次出现,使用list.remove:

>>> xs = ['a', 'b', 'c', 'd']
>>> xs.remove('b')
>>> print(xs)
['a', 'c', 'd']

要移除所有出现的元素,使用列表推导式:

>>> xs = ['a', 'b', 'c', 'd', 'b', 'b', 'b', 'b']
>>> xs = [x for x in xs if x != 'b']
>>> print(xs)
['a', 'c', 'd']

其他回答

正如许多其他答案所述,list.remove()将工作,但如果项不在列表中则抛出ValueError。在python 3.4+中,有一个有趣的方法来处理这个问题,使用suppress contextmanager:

from contextlib import suppress
with suppress(ValueError):
    a.remove('b')

考虑:

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

要去除所有的事件,可以使用python中的filter函数。 例如,它看起来是这样的:

a = list(filter(lambda x: x!= 2, a))

因此,它将保留a != 2的所有元素。

只要拿出其中一项使用

a.remove(2)

如果你知道要删除什么值,这里有一个简单的方法(就像我能想到的一样简单):

a = [0, 1, 1, 0, 1, 2, 1, 3, 1, 4]
while a.count(1) > 0:
    a.remove(1)

你会得到 [0,0,2,3,4]

 list1=[1,2,3,3,4,5,6,1,3,4,5]
 n=int(input('enter  number'))
 while n in list1:
    list1.remove(n)
 print(list1)

如果你的元素是不同的,那么一个简单的集合差异就可以了。

c = [1,2,3,4,'x',8,6,7,'x',9,'x']
z = list(set(c) - set(['x']))
print z
[1, 2, 3, 4, 6, 7, 8, 9]