📜  Python – 按列表中的第 K 个元素过滤元组

📅  最后修改于: 2022-05-13 01:54:31.894000             🧑  作者: Mango

Python – 按列表中的第 K 个元素过滤元组

给定一个元组列表,按 List 中存在的第 K 个元素进行过滤。

方法#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)]