发现 Python 中元组列表中包含给定元素的元组
列表的元素可以是元组。本文我们将了解如何识别包含特定搜索元素(字符串)的元组。
使用 in 和条件
我们可以设计带有 in 条件的后续内容。在 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 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)]使用 filter
我们使用 filter 函数和 Lambda 函数。在 filter 条件中,我们使用 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)]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP