当我尝试从列表中删除一个元素时,如何忽略 ValueError? [英] How can I ignore ValueError when I try to remove an element from a list?

查看:22
本文介绍了当我尝试从列表中删除一个元素时,如何忽略 ValueError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在列表 a<中不存在 x 时调用 a.remove(x),我如何忽略不在列表中"错误消息/代码>?

这是我的情况:

<预><代码>>>>a = 范围(10)>>>一个[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>>a.移除(10)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中ValueError: list.remove(x): x 不在列表中>>>a.移除(9)

解决方案

一个好的线程安全的方法是尝试并忽略异常:

尝试:a.移除(10)除了值错误:pass #什么都不做!

How can I ignore the "not in list" error message if I call a.remove(x) when x is not present in list a?

This is my situation:

>>> 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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆