当我尝试从列表中删除元素时,如何忽略ValueError?

时间:2012-03-28 20:42:54

标签: python list error-handling elements

如果在列表a.remove(x)中不存在x时拨打a,我该如何忽略“不在列表中”错误消息?

这是我的情况:

>>> a = range(10)
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a.remove(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
>>> a.remove(9)

7 个答案:

答案 0 :(得分:36)

执行此操作的良好且线程安全的方法是尝试并忽略异常:

try:
    a.remove(10)
except ValueError:
    pass  # do nothing!

答案 1 :(得分:24)

我个人考虑使用set而不是list,只要您的元素的顺序不一定重要。然后你可以使用discard方法:

>>> S = set(range(10))
>>> S
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> S.remove(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 10
>>> S.discard(10)
>>> S
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

答案 2 :(得分:15)

作为忽略ValueError的替代方法

try:
    a.remove(10)
except ValueError:
    pass  # do nothing!

我认为以下内容更为直接和可读:

if 10 in a:
    a.remove(10)

答案 3 :(得分:3)

列表理解如何?

a = [x for x in a if x != 10]

答案 4 :(得分:0)

一种更好的方法是

source_list = list(filter(lambda x: x != element_to_remove,source_list))

因为在更复杂的程序中,ValueError的异常也可能会引起其他问题,并且这里给出了一些答案,因此将其丢弃,从而在产生更多可能出现的问题的同时将其丢弃。

答案 5 :(得分:0)

当我只想确保条目不在列表,字典或集合中时,我像这样使用contextlib:

import contextlib

some_list = []
with contextlib.suppress(ValueError):
    some_list.remove(10)

some_set = set()
some_dict = dict()
with contextlib.suppress(KeyError):
    some_set.remove('some_value')
    del some_dict['some_key']

答案 6 :(得分:-2)

您输入了错误的输入。 语法:list.remove(x)

,x是列表的元素。 在删除括号中,输入列表中已有的内容。 例如:a.remove(2)

我输入2是因为它在列表中。 我希望这些数据能为您提供帮助。

相关问题