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

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

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

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

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

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


当前回答

如果您要检查一次集合中是否存在值,那么可以使用“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

其他回答

如果在列表中找到x,则使用list.index(x)返回x的索引,如果找不到x,则返回#ValueError消息,您可以使用list.count(x)来返回列表中x的出现次数(验证x是否确实在列表中),否则返回0(如果没有x)。count()很酷的一点是它不会破坏代码,也不会在找不到x时要求抛出异常。

查找第一个事件

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

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

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

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

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

另一种选择是:您可以使用列表中的if项检查列表中的某个项是否存在,但这是顺序O(n)。如果您正在处理大量项目列表,而您需要知道的只是某个项目是否是列表中的一员,则可以先将列表转换为集合,并利用恒定时间集查找:

my_set = set(my_list)
if item in my_set:  # much faster on average than using a list
    # do something

并非所有情况下都是正确的解决方案,但在某些情况下,这可能会给您带来更好的性能。

请注意,使用set(my_list)创建集合也是O(n),因此如果只需要这样做一次,那么这样做不会更快。如果您需要重复检查成员资格,那么在创建初始集之后,每次查找都将是O(1)。