Python – 按列表中的第 K 个元素过滤元组
给定一个元组列表,按 List 中存在的第 K 个元素进行过滤。
Input : test_list = [(“GFg”, 5, 9), (“is”, 4, 3), (“best”, 10, 29)], check_list = [4, 2, 3, 10], K = 2
Output : [(‘is’, 4, 3)]
Explanation : 3 is 2nd element and present in list, hence filtered tuple.
Input : test_list = [(“GFg”, 5, 9), (“is”, 4, 3), (“best”, 10, 29)], check_list = [4, 2, 3, 10], K = 1
Output : [(‘is’, 4, 3), (‘best’, 10, 29)]
Explanation : 4 and 10 are 1st elements and present in list, hence filtered tuples.
方法#1:使用列表推导
在此,我们使用列表推导检查 Tuple 的第 K 个元素的每个元素是否存在于列表中,并使用 in运算符测试包含。
Python3
# Python3 code to demonstrate working of
# Filter Tuples by Kth element from List
# Using list comprehension
# initializing list
test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)]
# printing original list
print("The original list is : " + str(test_list))
# initializing check_list
check_list = [4, 2, 8, 10]
# initializing K
K = 1
# checking for presence on Kth element in list
# one liner
res = [sub for sub in test_list if sub[K] in check_list]
# printing result
print("The filtered tuples : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter Tuples by Kth element from List
# Using filter() + lambda
# initializing list
test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)]
# printing original list
print("The original list is : " + str(test_list))
# initializing check_list
check_list = [4, 2, 8, 10]
# initializing K
K = 1
# filter() perform filter, lambda func. checks for presence
# one liner
res = list(filter(lambda sub: sub[K] in check_list, test_list))
# printing result
print("The filtered tuples : " + str(res))
输出
The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
The filtered tuples : [('is', 4, 3), ('best', 10, 29)]
方法 #2:使用 filter() + lambda
在此,lambda函数检查元素是否存在,并且 filter 执行过滤元组的任务。
Python3
# Python3 code to demonstrate working of
# Filter Tuples by Kth element from List
# Using filter() + lambda
# initializing list
test_list = [("GFg", 5, 9), ("is", 4, 3), ("best", 10, 29)]
# printing original list
print("The original list is : " + str(test_list))
# initializing check_list
check_list = [4, 2, 8, 10]
# initializing K
K = 1
# filter() perform filter, lambda func. checks for presence
# one liner
res = list(filter(lambda sub: sub[K] in check_list, test_list))
# printing result
print("The filtered tuples : " + str(res))
输出
The original list is : [('GFg', 5, 9), ('is', 4, 3), ('best', 10, 29)]
The filtered tuples : [('is', 4, 3), ('best', 10, 29)]