天天看点

列表是否包含简短的包含功能?

本文翻译自:Is there a short contains function for lists?

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?:

我看到人们正在使用

any

来收集另一个列表,以查看列表中是否存在某个项目,但是有一种快速的方法吗?:
if list.contains(myItem):
    # do something
           

#1楼

参考:https://stackoom.com/question/sGly/列表是否包含简短的包含功能

#2楼

You can use this syntax:

您可以使用以下语法:
if myItem in list:
    # do something
           

Also, inverse operator:

同样,逆运算符:
if myItem not in list:
    # do something
           

It's work fine for lists, tuples, sets and dicts (check keys).

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

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

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

#3楼

The list method

index

will return

-1

if the item is not present, and will return the index of the item in the list if it is present.

如果该项目不存在,则列表方法

index

将返回

-1

如果该项目存在,则将返回列表中该项目的索引。

Alternatively in an

if

statement you can do the following:

或者,在

if

语句中,您可以执行以下操作:
if myItem in list:
    #do things
           

You can also check if an element is not in a list with the following if statement:

您还可以使用以下if语句检查元素是否不在列表中:
if myItem not in list:
    #do things
           

#4楼

In addition to what other have said, you may also be interested to know that what

in

does is to call the

list.__contains__

method, that you can define on any class you write and can get extremely handy to use python at his full extent.

除了别人所说的以外,您可能还想知道

in

做什么是调用

list.__contains__

方法,您可以在编写的任何类上定义该方法,并且可以在充分利用python的情况下非常方便。

A dumb use may be:

愚蠢的用途可能是:
>>> class ContainsEverything:
    def __init__(self):
        return None
    def __contains__(self, *elem, **k):
        return True


>>> a = ContainsEverything()
>>> 3 in a
True
>>> a in a
True
>>> False in a
True
>>> False not in a
False
>>>         
           

#5楼

I came up with this one liner recently for getting

True

if a list contains any number of occurrences of an item, or

False

if it contains no occurrences or nothing at all.

我最近想出了这条线,是因为如果列表中包含某项事件的出现次数为

True

则为

True

如果该列表中没有事件的发生或

False

则为

False

Using

next(...)

gives this a default return value (

False

) and means it should run significantly faster than running the whole list comprehension.

使用

next(...)

为它提供默认的返回值(

False

),这意味着它的运行速度应比整个列表理解的运行速度明显快。

list_does_contain = next((True for item in list_to_test if item == test_item), False)