问题:列表是否包含简短的包含功能?
我看到人们正在使用any
另一个列表来查看列表中是否存在某项,但是有一种快速的方法吗?
if list.contains(myItem):
# do something
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?:
if list.contains(myItem):
# do something
回答 0
您可以使用以下语法:
if myItem in list:
# do something
同样,逆运算符:
if myItem not in list:
# do something
它适用于列表,元组,集合和字典(检查键)。
请注意,这是列表和元组中的O(n)操作,而集合和字典中是O(1)操作。
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.
回答 1
除了别人说过的话,您可能还想知道什么in
是调用list.__contains__
方法,您可以在编写的任何类上定义该方法,并且可以非常方便地全面使用python。
愚蠢的用途可能是:
>>> 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
>>>
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.
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
>>>
回答 2
我最近想出了这条衬垫,用于获取True
列表中是否包含任何数量的项目,或者该列表中不包含任何项目或False
根本不包含任何项目。使用next(...)
会给它提供默认的返回值(False
),这意味着它的运行速度应比运行整个列表理解的速度快得多。
list_does_contain = next((True for item in list_to_test if item == test_item), False)
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. Using next(...)
gives this a default return value (False
) and means it should run significantly faster than running the whole list comprehension.
list_does_contain = next((True for item in list_to_test if item == test_item), False)
回答 3
如果该项目不存在,则list方法index
将返回,-1
如果该项目存在,则将返回该项目在列表中的索引。或者,if
您可以在语句中执行以下操作:
if myItem in list:
#do things
您还可以使用以下if语句检查元素是否不在列表中:
if myItem not in list:
#do things
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. Alternatively in an if
statement you can do the following:
if myItem in list:
#do things
You can also check if an element is not in a list with the following if statement:
if myItem not in list:
#do things