列表有简短的包含功能吗? [英] Is there a short contains function for lists?

查看:16
本文介绍了列表有简短的包含功能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到人们正在使用 any 来收集另一个列表以查看列表中是否存在某个项目,但是有没有一种快速的方法来做这样的事情?

I see people are using any to gather another list to see if an item exists in a list, but is there a quick way to just do something like this?

if list.contains(myItem):
    # do something

推荐答案

您可以使用以下语法:

if myItem in some_list:
    # do something

另外,逆运算符:

if myItem not in some_list:
    # do something

它适用于列表、元组、集合和字典(检查键).

It works fine for lists, tuples, sets and dicts (check keys).

注意,这是列表和元组中的 O(n) 操作,但集合和字典中的 O(1) 操作.

Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts.

这篇关于列表有简短的包含功能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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