我使用以下方法检查项目是否在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)

其他回答

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

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

在与dict()的列表()一起工作时:

a = [ {"a":1}, {"b":1, "c":1} ]

b = {"c":1 , "b":1} # <-- No matter the order
    
if b in a: 
    print("b is in a")

至少在Python 3.8.10中,无论顺序如何

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

你说在我的几次试验中,可能有空白和换行干扰。这就是为什么我给你这个解决方案。

myList=[" test","ok","ok1"]
item = "test"#someSortOfSelection()
if  True in list(map(lambda el : item in el ,myList)):
    doMySpecialFunction(item)

查找第一个事件

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

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