您现在的位置是:课程教程文章

python怎么查找列表是否存在该元素

2023-12-18 18:44课程教程文章 人已围观

python中可以使用index()方法查找列表中是否存在某元素。index() 函数用于从列表中找出某个值第一个匹配项的索引位置。该方法返回查找对象的索引位置,如果没有找到对象则抛出异常。

示例:

存在指定元素的情况:

test_list = [ 1, 6, 3, 5, 3, 4 ]
test_list.index(1)

输出结果:

0

不存在指定元素的情况:

test_list = [ 1, 6, 3, 5, 3, 4 ]
test_list.index(0)

输出结果如下:

-------------------------------------------------------

ValueError            Traceback (most recent call last)

<ipython-input-37-b545efee4fc5> in <module>

      1 test_list = [ 1, 6, 3, 5, 3, 4 ]

----> 2 test_list.index(0)

ValueError: 0 is not in list

更多Python知识请关注Python自学网。

课程教程:python怎么查找列表是否存在该元素

上一篇:python程序里rt是什么意思?

下一篇:没有了

站点信息

  • 文章统计篇文章