发布时间:2022-06-09 09:32:42 人气:136 作者:多测师
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)
in
1 test_list = [ 1, 6, 3, 5, 3, 4 ]
----> 2 test_list.index(0)
ValueError: 0 is not in list
以上内容为大家介绍了python怎么查找列表是否存在该元素,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/