• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

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

python 搞java代码 3年前 (2022-05-21) 28次浏览 已收录 0个评论

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

示例:

存在指定元素的情况:

test_<a href="https://www.gaodaima.com/tag/list" title="查看更多关于list的文章" target="_blank">list</a> = [ 1, 6, 3, 5, 3, 4 ]
<a href="https://www.gaodaima.com/tag/test" title="查看更多关于test的文章" target="_blank">test</a>_list.index(1)

www#gaodaima.com来源gaodai$ma#com搞$$代**码网搞代码

输出结果:

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知识请关注搞代码网。

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:python怎么查找列表是否存在该元素

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址