从Python中的元组列表中找到包含给定元素的元组
列表可以将元组作为其元素。在本文中,我们将学习如何识别包含特定搜索元素(字符串)的元组。
有条件
我们可以根据情况设计跟踪。之后,我们可以提及条件或条件组合。
示例
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
#Given list
print("Given list:\n",listA)
print("Check value:\n",test_elem)
# Uisng for and if
res = [item for item in listA
if item[0] == test_elem and item[1] >= 2]
# printing res
print("The tuples satisfying the conditions:\n ",res)输出结果
运行上面的代码给我们以下结果-
Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]带过滤器
我们将过滤器功能与Lambda函数一起使用。在过滤条件下,我们使用in运算符检查元组中元素的存在。
示例
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
#Given list
print("Given list:\n",listA)
print("Check value:\n",test_elem)
# Uisng lambda and in
res = list(filter(lambda x:test_elem in x, listA))
# printing res
print("The tuples satisfying the conditions:\n ",res)输出结果
运行上面的代码给我们以下结果-
Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]热门推荐
10 女生 节日祝福语简短大气
11 宝宝满月写真祝福语简短
12 下雨开工吉祥祝福语简短
13 生日果酒祝福语简短独特
14 大雪生日祝福语大全简短
15 祖国七十华诞简短祝福语
16 表达朋友的祝福语简短
17 小姨生日祝福语简短独特
18 顾客简短祝福语大全集