迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Python >

检查索引是否存在于 Python 列表中

作者:迹忆客 最近更新:2023/12/17 浏览次数:

我们将介绍两种使用列表范围和 IndexError 异常检查列表索引是否存在的方法。


使用列表范围检查索引是否存在于 Python 列表中

我们将不得不检查索引是否存在于 0 的范围内和列表的长度。

fruit_list = ["Apple", "Banana", "Pineapple"]

for index in range(0, 5):
    if 0 <= index < len(fruit_list):
        print("Index ", index, " in range")
    else:
        print("Index ", index, " not in range")

输出:

Index  0  in range
Index  1  in range
Index  2  in range
Index  3  not in range
Index  4  not in range

使用 IndexError 检查索引是否存在于 Python 列表中

当我们尝试访问列表中不存在的索引时,它会引发 IndexError 异常。

fruit_list = ["Apple", "Banana", "Pineapple"]

for index in range(0, 5):
    try:
        fruit_list[index]
        print("Index ", index, " in range")
    except IndexError:
        print("Index ", index, " does not exist")
Index  0  in range
Index  1  in range
Index  2  in range
Index  3  does not exist
Index  4  does not exist

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Pandas read_csv()函数

发布时间:2024/04/24 浏览次数:254 分类:Python

Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。

Pandas 追加数据到 CSV 中

发布时间:2024/04/24 浏览次数:352 分类:Python

本教程演示了如何在追加模式下使用 to_csv()向现有的 CSV 文件添加数据。

Pandas 多列合并

发布时间:2024/04/24 浏览次数:628 分类:Python

本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。

Pandas loc vs iloc

发布时间:2024/04/24 浏览次数:837 分类:Python

本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便