在 Python 中从元组列表中查找包含给定元素的元组
pythonserver side programmingprogramming更新于 2026/1/22 19:56:17
列表可以包含元组作为其元素。在本文中,我们将学习如何识别包含特定搜索元素(字符串)的元组。
使用 in 和条件
我们可以设计一个跟在 in 后面的条件。在 in 之后,我们可以提及条件或条件组合。
示例
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
# 给定列表
print("给定列表:\n",listA)
print("检查值:\n",test_elem)
# 使用 for and if
res = [item for item in listA
if item[0] == test_elem and item[1] >= 2]
# 打印 res
print("The tuples satisfying the conditions:\n ",res)
输出
运行上述代码得到以下结果 −
给定列表:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
检查值:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]
使用过滤器
我们将 filter 过滤器函数与 Lambda 函数一起使用。在过滤条件中,我们使用 in 运算符来检查元组中是否存在元素。
示例
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
# 给定列表
print("给定列表:\n",listA)
print("检查值:\n",test_elem)
# 使用 lambda 和 in
res = list(filter(lambda x:test_elem in x, listA))
# 打印 res
print("The tuples satisfying the conditions:\n ",res)
输出
运行上述代码得到以下结果 −
给定列表:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
检查值:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

