Python List Contains:如何检查项目是否存在于列表中

2,003 阅读6分钟

Python List Contains | How To Check If Item Exists In List

在机器学习、人工智能、甚至网络开发的过程中,我们通常会遇到这样的问题:我们需要测试一个给定的列表中的特定项目是否为子串。 要在Python中检查列表是否包含特定的元素,可以使用**"in "** 操作符或**"not in "** 操作符。让我们详细地探讨一下这个话题。

Python 列表包含

要在Python检查 列表是否包含某个元素,使用**"in"** 操作符。in" 操作符检查列表是否包含一个特定的项目。它还可以使用list.count()函数检查元素是否存在于列表中。

Python list 是一个重要的容器,因为它把所有数据类型的元素作为一个集合来存储。Python 的 "in 操作符" 是检查一个项目是否存在于列表中的最方便的方法。

如果一个项目存在于列表中,这种方法返回True,如果一个项目不存在则返回False。列表不需要进行排序就可以实行这种检查方法。

检查项目是否存在于列表中

要检查项目是否存在于列表中,可以使用 Python "in 操作符"。例如,我们可以在 if 条件下使用 "in" 操作符,如果项目存在于列表中,则条件返回True,如果不存在,则返回False

请看下面的 Python in 操作符的语法。

语法

item in List

返回值

如果列表中存在一个项目,它将返回True,否则返回False

# app.py

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

if 'S Eductation' in listA:
    print("Yes, 'S Eductation' found in List : ", listA)

输出

python3 app.py
Yes, 'S Eductation' found in List :  ['Stranger Things', 'S Education', 'Game of Thrones']

让我们举一个例子,我们在列表中没有找到一个项目。

# app.py

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

if 'Dark' in listA:
    print("Yes, 'S Eductation' found in List : ", listA)
else:
    print("Nope, 'Dark' not found in the list")

输出结果

python3 app.py
Nope, 'Dark' Not found in the list

列表中不包含暗元素,所以它返回False, 并且执行 else 块。

使用List comprehension检查列表中存在的项目。

我们也可以使用列表理解法来检查项目是否存在于Python 列表中。

请看下面的代码。

# app.py

data_string = "The last season of Game of Thrones was not good"

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

print("The original string : " + data_string)

print("The original list : " + str(listA))

res = [ele for ele in listA if(ele in data_string)]

print("Does string contain any list element : " + str(bool(res)))

输出

python3 app.py
The original string : The last season of Game of Thrones was not good
The original list : ['Stranger Things', 'S Education', 'Game of Thrones']
Does string contain any list element : True

列表理解提供了一种创建列表的简明方式。

它由包含表达式的括号组成,后面是一个for 子句,然后是零个或多个 for 或 if 子句。表达式可以是任何东西,这意味着你可以 把所有类型的对象放在列表中。

结果将是在 for和if子句的上下文中对表达式进行评估后产生的新列表 。

在我们的例子中,我们对列表进行检查,如果能找到一个匹配项,也用字符串项进行检查,并返回 true。

让我们看看字符串中是否包含列表中某个项目中不存在的单词。

# app.py

data_string = "The last season of BoJack Horseman was good"

# initializing test list
listA = ['Stranger Things', 'S Education', 'Game of Thrones']

# printing original string
print("The original string : " + data_string)

# printing original list
print("The original list : " + str(listA))

# using list comprehension
# checking if string contains list element
res = [ele for ele in listA if(ele in data_string)]

# print result
print("Does string contain any list element : " + str(bool(res)))

输出

python3 app.py
The original string: The last season of BoJack Horseman was good
The original list : ['Stranger Things', 'S Education', 'Game of Thrones']
Does string contain any list element: False

使用 list.count() 检查元素是否存在于列表中。

要检查项目是否存在于 Python 列表中,请使用 list.count() 方法。

list.count()函数的语法如下。

list.count(elem)

Python List count(item) 方法返回列表中给定元素的出现次数。如果它大于 0,说明列表中存在一个给定的项目。

# app.py

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

if listA.count('Stranger Things') > 0:
    print("Yupp, 'Stranger Things' found in List : ", listA)

输出

python3 app.py
Yupp, 'Stranger Things' found in List :  ['Stranger Things', 'S Education', 'Game of Thrones']

使用any()检查一个元素是否存在于列表中

使用Python any()函数是最经典的方法,你可以有效地执行这个任务。any()函数检查一个字符串中每个列表元素的匹配情况。

# app.py

data_string = "The last season of Game of Thrones was not good"

listA = ['Stranger Things', 'S Education', 'Game of Thrones']

print("The original string : " + data_string)

print("The original list : " + str(listA))

res = any(item in data_string for item in listA)

print("Does string contain 'Game of Thrones' list element: " + str(res))

输出结果

python3 app.py
The original string : The last season of Game of Thrones was not good
The original list : ['Stranger Things', 'S Education', 'Game of Thrones']
Does string contain 'Game of Thrones' list element: True

从输出结果来看,权力的游戏存在于列表中。

使用 not in 反向操作符检查列表中是否包含一个项目。

Python "not in"是一个内置的操作符,如果它在指定的序列中没有找到一个变量,则评估为True,否则为False

要检查列表是否包含一个特定的项目,可以使用 not in inverse 操作符。让我们看看下面的例子。

listA = ['Stranger Things', 'S Education', 'Game of Thrones']
if 'Witcher' not in listA:
    print("Yes, 'Witcher' is not found in List : ", listA)

输出

python3 app.py
Yes, 'Witcher' is not found in List :  ['Stranger Things', 'S Education', 'Game of Thrones']

Python in 和 not in 运算符对列表、图元、集合和dicts(检查键) 都能正常工作。

Python all() 方法检查列表是否存在于另一个列表中

在这个程序中,你将学习如何检查 Python 列表是否包含另一个列表的所有项目,并使用 python print() 函数显示结果。

我们将使用两个具有重叠值的列表。其中一个是大的,它容纳了第二个列表的所有项目。

  1. List1 - List1 包含另一个列表的全部或部分项目。
  2. List2 - 它是第一个列表的子集。

请看下面的代码。

# app.py

List1 = ['Homer',  'Bart', 'Lisa', 'Maggie', 'Lisa']

List2 = ['Bart', 'Homer', 'Lisa']

check = all(item in List1 for item in List2)

if check is True:
    print("The list {} contains all elements of the list {}".format(List1, List2))
else:
    print("No, List1 doesn't have all elements of the List2.")

输出

python3 app.py
The list ['Homer', 'Bart', 'Lisa', 'Maggie', 'Lisa'] contains all elements of the list ['Bart', 'Homer', 'Lisa']

你可以看到,第一个列表包含第二个列表的所有元素。这是因为我们已经用all()方法检查了第一个列表。

总结

你可以用很多方法来确定一个项目是否存在于列表中。例如,我们已经看到了以下几种方法。

  1. 使用Python "in"操作符
  2. 使用 Python 列表理解法
  3. 使用list.count()方法
  4. 使用Python any()函数

本教程就到此为止。