Python|根据列表元素的存在过滤元组
有时,在处理记录时,我们可能会遇到一个问题,即我们必须从元组列表中过滤所有元组,该列表至少包含一个列表中的元素。这可以在许多处理数据的领域中得到应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用列表推导
使用列表理解是一种蛮力方法,可以简写执行此任务。在此,我们只检查每个元组并检查它是否包含目标列表中的任何元素。
# Python3 code to demonstrate working of
# Filter tuples according to list element presence
# using list comprehension
# initialize list of tuple
test_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
# initialize target list
tar_list = [6, 10]
# printing original tuples list
print("The original list : " + str(test_list))
# Filter tuples according to list element presence
# using list comprehension
res = [tup for tup in test_list if any(i in tup for i in tar_list)]
# printing result
print("Filtered tuple from list are : " + str(res))
输出 :
The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
Filtered tuple from list are : [(1, 4, 6), (1, 10)]
方法 #2:使用set()
+ 列表推导
可以通过将容器转换为set()
来优化上述方法,以减少重复并执行 & 操作以获取所需的记录。
# Python3 code to demonstrate working of
# Filter tuples according to list element presence
# using set() + list comprehension
# initialize list of tuple
test_list = [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
# initialize target list
tar_list = [6, 10]
# printing original tuples list
print("The original list : " + str(test_list))
# Filter tuples according to list element presence
# using set() + list comprehension
res = [tup for tup in test_list if (set(tar_list) & set(tup))]
# printing result
print("Filtered tuple from list are : " + str(res))
输出 :
The original list : [(1, 4, 6), (5, 8), (2, 9), (1, 10)]
Filtered tuple from list are : [(1, 4, 6), (1, 10)]