Python - 使用任何布尔值提取行
给定一个布尔矩阵,提取包含至少一个布尔 True 值的行。
Input : test_list = [[False, False], [True, True, True], [False, True], [False]]
Output : [[True, True, True], [False, True]]
Explanation : All rows with atleast 1 True extracted.
Input : test_list = [[False, False], [False]]
Output : []
Explanation : No rows with even one True.
方法 #1:使用列表理解+ any()
在这里,我们使用 any() 检查任何元素是否为布尔真,并且列表理解用于矩阵中行的迭代任务。
Python3
# Python3 code to demonstrate working of
# Extract Row with any Boolean True
# Using list comprehension + any()
# initializing list
test_list = [[False, False], [True, True, True], [False, True], [False]]
# printing original list
print("The original list is : " + str(test_list))
# using any() to check for any True value
res = [sub for sub in test_list if any(ele for ele in sub)]
# printing result
print("Extracted Rows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Row with any Boolean True
# Using any() + filter() + lambda
# initializing list
test_list = [[False, False], [True, True, True], [False, True], [False]]
# printing original list
print("The original list is : " + str(test_list))
# using any() to check for any True value
# filter() to perform filtering
res = list(filter(lambda sub : any(ele for ele in sub), test_list))
# printing result
print("Extracted Rows : " + str(res))
输出:
The original list is : [[False, False], [True, True, True], [False, True], [False]] Extracted Rows : [[True, True, True], [False, True]]
方法#2:使用 any() + filter() + lambda
在这里,我们使用 any() 和 filter() 执行检查任何 True 值的任务,并且 lambda 用于过滤掉匹配的行。
蟒蛇3
# Python3 code to demonstrate working of
# Extract Row with any Boolean True
# Using any() + filter() + lambda
# initializing list
test_list = [[False, False], [True, True, True], [False, True], [False]]
# printing original list
print("The original list is : " + str(test_list))
# using any() to check for any True value
# filter() to perform filtering
res = list(filter(lambda sub : any(ele for ele in sub), test_list))
# printing result
print("Extracted Rows : " + str(res))
输出:
The original list is : [[False, False], [True, True, True], [False, True], [False]] Extracted Rows : [[True, True, True], [False, True]]