如何在不获取“IndexError:列表索引超出范围”的情况下检查项目是否存在?

2024-06-15 21:08:05 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有以下列表:

common_list = ['Potato', 'Tomato', 'Carrot']

我想检查common_list[3]是否存在;如果没有,我想添加一些内容。以下是我尝试过的:

if common_list[2] and not common_list[3]:
    common_list.insert(3, 'Lemon')

但它给了我一个错误:

IndexError: list index out of range

Tags: and内容列表indexif错误notcommon
2条回答

这完全取决于您想要执行哪种检查。这里有一些可能性

检查有三个项目:

if len(common_list) == 3:
    common_list.append('Lemon')

检查少于四项:

if len(common_list) < 4:
    common_list.append('Lemon')

检查是否没有第四项,或者第四项是否存在,但设置为None

if len(common_list) < 4 or common_list[4] is None:
    common_list.append('Lemon')

检查列表是否尚未包含'Lemon'

if 'Lemon' not in common_list:
    common_list.append('Lemon')

如果可以通过简单的if检查避免异常,则不要触发并捕获异常。这是一种糟糕的风格。异常代价高昂,捕获它们的速度很慢。尝试只在真正的异常情况下使用它们,如果实际发生错误,您会感到惊讶

也许你会尝试异常方法

common_list = ['Potato', 'Tomato', 'Carrot']
try:
    common_list[3]
except IndexError:
    common_list.insert(3, 'Lemon')

相关问题 更多 >