在 Python 中检查列表列表中是否存在元素
pythonserver side programmingprogramming更新于 2025/12/25 22:36:17
列表可以嵌套,这意味着列表的元素本身就是列表。在本文中,我们将了解如何找出给定元素是否存在于子列表中,而子列表本身又是更大列表中的元素。
使用任何
我们首先搜索元素是否存在于子列表中,以及子列表是否存在于列表中。如果其中任何一个为真,我们就可以说该元素存在于列表中。
示例
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_element = -8
# 给定列表
print("给定列表:\n",listA)
print("要搜索的元素:",search_element)
# 使用
if any(search_element in sublist for sublist in listA):
print("Present")
else:
print("Not Present")
输出
运行上述代码得到以下结果 −
('给定列表 :\n', [[-9, -1, 3], [11, -8], [-4, 434, 0]])
('要搜索的元素: ', -8)
Present
使用 in
在此方法中,我们使用 in 运算符进行简单搜索。如果项目是子列表的一部分,而子列表也是外部列表的一部分,则我们接受该元素为存在。我们进行两次检查,一次检查存在,另一次检查不存在。
示例
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_element = -8
# 给定列表
print("Given List :\n", listA)
print("Element to Search: ",search_element)
# 使用 in
if search_element in (item for sublist in listA for item in sublist):
print("Present")
else:
print("Not Present")
search_element = 13
print("New Element to Search: ",search_element)
# 使用 in
if search_element in (item for sublist in listA for item in sublist):
print("Present")
else:
print("Not Present")
输出
运行上述代码得到以下结果 −
Given List : [[-9, -1, 3], [11, -8], [-4, 434, 0]] Element to Search: -8 Present New Element to Search: 13 Not Present
使用 chain
使用 itertools 模块中的 chain 方法,我们可以扩展子列表的列表,并使用 in 方法继续检查元素是否存在。
示例
from itertools import chain
listA = [[-9, -1, 3], [11, -8],[-4,434,0]]
search_element = -8
# 给定列表
print("Given List :\n", listA)
print("Element to Search: ",search_element)
# 使用 in
if search_element in chain(*listA):
print("Present")
else:
print("Not Present")
search_element = 13
print("New Element to Search: ",search_element)
# 使用 in
if search_element in chain(*listA):
print("Present")
else:
print("Not Present")
输出
运行上述代码得到以下结果 −
Given List : [[-9, -1, 3], [11, -8], [-4, 434, 0]] Element to Search: -8 Present New Element to Search: 13 Not Present
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

