📜  Python - 过滤具有所需元素的行

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

Python - 过滤具有所需元素的行

给定一个矩阵,从其他列表中过滤具有所需元素的行。

方法 #1:使用列表理解+ all()

在这种情况下,我们使用列表中的列表理解来执行迭代和过滤,并使用 all() 检查每行中存在的所有元素。

Python3
# Python3 code to demonstrate working of
# Filter rows with required elements
# Using list comprehension + all()
  
# initializing list
test_list = [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing check_list
check_list = [4, 6, 2, 8]
  
# using in operator to check for presence
res = [sub for sub in test_list if all(ele in check_list for ele in sub)]
  
# printing result
print("Filtered rows : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Filter rows with required elements
# Using filter() + lambda + all()
  
# initializing list
test_list = [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing check_list 
check_list = [4, 6, 2, 8]
  
# using in operator to check for presence
# filter(), getting all rows checking from check_list
res = list(filter(lambda sub : all(ele in check_list for ele in sub), test_list))
  
# printing result 
print("Filtered rows : " + str(res))


输出:

方法 #2:使用filter() + lambda + all()

在这种情况下,过滤任务是使用 filter() 和 lambda 完成的,all() 用于从中提取清单中存在的所有元素的任务。

蟒蛇3

# Python3 code to demonstrate working of 
# Filter rows with required elements
# Using filter() + lambda + all()
  
# initializing list
test_list = [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing check_list 
check_list = [4, 6, 2, 8]
  
# using in operator to check for presence
# filter(), getting all rows checking from check_list
res = list(filter(lambda sub : all(ele in check_list for ele in sub), test_list))
  
# printing result 
print("Filtered rows : " + str(res))

输出: