尝试从列表中删除元素时,如何忽略ValueError? [英] How can I ignore ValueError when I try to remove an element from a list?
本文介绍了尝试从列表中删除元素时,如何忽略ValueError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果在列表 a <中没有
x
的情况下调用 a.remove(x)
,如何忽略不在列表中"错误消息/code>?
How can I ignore the "not in list" error message if I call a.remove(x)
when x
is not present in list 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)
推荐答案
一种做到这一点的线程安全的好方法就是尝试一下,忽略异常:
A good and thread-safe way to do this is to just try it and ignore the exception:
try:
a.remove(10)
except ValueError:
pass # do nothing!
这篇关于尝试从列表中删除元素时,如何忽略ValueError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文