我使用以下方法检查项目是否在my_list中:

if item in my_list:
    print("Desired item is in list")

“if item in my_list:”是在列表中查找项目的最“Python”方式吗?

编辑:这个问题被认为是重复的,但我并不完全相信:这里这个问题大致上是“在列表中查找元素的最Python方式是什么”。这个问题的第一个答案在所有Python方法中都非常广泛。

而在链接的重复问题及其对应的答案上,重点大致仅限于Python中的“in”关键字。与目前的问题相比,我认为这确实是一个限制。

我认为当前问题的答案比拟议的重复问题/答案更为相关和详细。


当前回答

定义和使用

count()方法返回具有指定值的元素数。

语法

list.count(value)

例子:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

问题示例:

item = someSortOfSelection()

if myList.count(item) >= 1 :

    doMySpecialFunction(item)

其他回答

如果您要检查一次集合中是否存在值,那么可以使用“in”运算符。然而,如果您要检查不止一次,那么我建议使用平分模块。请记住,使用平分模块数据必须进行排序。因此,您对数据进行一次排序,然后可以使用二等分。在我的机器上使用平分模块比使用“in”运算符快大约12倍。

以下是使用Python 3.8及以上语法的代码示例:

import bisect
from timeit import timeit

def bisect_search(container, value):
    return (
      (index := bisect.bisect_left(container, value)) < len(container) 
      and container[index] == value
    )

data = list(range(1000))
# value to search
true_value = 666
false_value = 66666

# times to test
ttt = 1000

print(f"{bisect_search(data, true_value)=} {bisect_search(data, false_value)=}")

t1 = timeit(lambda: true_value in data, number=ttt)
t2 = timeit(lambda: bisect_search(data, true_value), number=ttt)

print("Performance:", f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")

输出:

bisect_search(data, true_value)=True bisect_search(data, false_value)=False
Performance: t1=0.0220, t2=0.0019, diffs t1/t2=11.71

虽然Niklas B.给出的答案非常全面,但当我们想在列表中查找某个项目时,有时获取其索引会很有用:

next((i for i, x in enumerate(lst) if [condition on x]), [default value])

如果您想在next中查找一个元素或None使用默认值,如果在列表中找不到该项,则不会引发StopIteration:

first_or_default = next((x for x in lst if ...), None)

检查字符串列表中的项目中是否没有额外的/不需要的空白。这是一个可能会干扰解释找不到项目的原因。

查找第一个事件

itertools中有一个解决方案:

def first_true(iterable, default=False, pred=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    If *pred* is not None, returns the first item
    for which pred(item) is true.

    """
    # first_true([a,b,c], x) --> a or b or c or x
    # first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
    return next(filter(pred, iterable), default)

例如,以下代码查找列表中的第一个奇数:

>>> first_true([2,3,4,5], None, lambda x: x%2==1)
3  

您可以复制/粘贴它或安装更多itertools

pip3 install more-itertools

其中该配方已经包括在内。