如何检查列表中是否包含特定元素 [英] How to check if a list has a certain element in it

查看:44
本文介绍了如何检查列表中是否包含特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

my_list = ["hi", "bye", "hi"]

说我不知道​​ my_list 中有什么,如何检查"bye" 是否是我列表中的一个元素.如果"bye" my_list 中的一个元素,那么我怎么知道它具有哪个索引(在这种情况下,"bye" my_list [1] )?

Say I don't know what is in my_list, how can I check if "bye" is an element in my list. And if "bye" is an element in my_list, then how can I know which index it has (for this case "bye" is in my_list[1])?

推荐答案

如何检查再见"是否是列表中的一个元素.

how can I check if "bye" is an element in my list.

my_list中的

"bye" in my_list

那我怎么知道它是哪个索引

then how can I know which index it is

my_list.index("bye")

您可以跳过第一步,因为如果您尝试查找列表中未包含的值的索引,则会收到一个值错误,可以通过以下方式处理:

You can skip the first step because if you try to find the index of a value that isn't in the list, you will get a value error which you can handle like this:

try:
    my_list.index("not here")
except ValueError:
    print("'not here' isn't in the list!!")

这篇关于如何检查列表中是否包含特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆