Python 列表有简短的包含功能吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12934190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:12:35  来源:igfitidea点击:

Is there a short contains function for lists?

pythonlistsearchcollectionscontains

提问by Joan Venge

I see people are using anyto 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

采纳答案by defuz

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).

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

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

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

回答by Mr. Squig

The list method indexwill return -1if the item is not present, and will return the index of the item in the list if it is present. Alternatively in an ifstatement you can do the following:

如果项目不存在,list 方法index将返回,-1如果项目存在,将返回列表中项目的索引。或者,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

回答by Ant

In addition to what other have said, you may also be interested to know that what indoes 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
>>>         

回答by Dustin Raimondi

I came up with this one liner recently for getting Trueif a list contains any number of occurrences of an item, or Falseif it contains no occurrences or nothing at all. Using next(...)gives this a default return value (False) and means it should run significantly faster than running the whole list comprehension.

我最近想出了这个一个班轮,以获取True列表是否包含任意数量的项目,或者False它是否不包含任何项目或根本不包含任何项目。Usingnext(...)给它一个默认返回值 ( False) 并意味着它应该比运行整个列表理解运行得快得多。

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

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