Python - 过滤具有所需元素的行
给定一个矩阵,从其他列表中过滤具有所需元素的行。
Input : test_list = [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]], check_list = [4, 6, 2, 8]
Output : [[2, 4, 6], [2, 4, 8]]
Explanation : All elements are from the check list.
Input : test_list = [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]], check_list = [6, 2, 8]
Output : []
Explanation : No list with all elements from check list.
方法 #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))
输出:
The original list is : [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]]
Filtered rows : [[2, 4, 6], [2, 4, 8]]
方法 #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))
输出:
The original list is : [[2, 4, 6], [7, 4, 3, 2], [2, 4, 8], [1, 1, 9]]
Filtered rows : [[2, 4, 6], [2, 4, 8]]