检查项目是否在数组/列表中 [英] Check if item is in an array / list

查看:35
本文介绍了检查项目是否在数组/列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个字符串数组,是否可以在不执行 for 循环的情况下检查字符串是否在数组中?具体来说,我正在寻找一种在 if 语句中执行此操作的方法,如下所示:

If I've got an array of strings, can I check to see if a string is in the array without doing a for loop? Specifically, I'm looking for a way to do it within an if statement, so something like this:

if [check that item is in array]:

推荐答案

假设你的意思是列表",你说数组",你可以这样做

Assuming you mean "list" where you say "array", you can do

if item in my_list:
    # whatever

这适用于任何集合,而不仅仅是列表.对于字典,它检查给定的键是否存在于字典中.

This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.

这篇关于检查项目是否在数组/列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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