Python - 用范围元素过滤行
给定一个矩阵,过滤包含给定数字范围内所有元素的所有行。
Input : test_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]], i, j = 2, 5
Output : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]]
Explanation : 2, 3, 4, 5 all are present in above rows.
Input : test_list = [[3, 2, 4, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]], i, j = 2, 5
Output : [[2, 3, 4, 5, 6, 7]]
Explanation : 2, 3, 4, 5 all are present in above rows.
方法 #1:使用all() +列表推导式
在这里,我们使用 all() 检查范围内的所有元素是否存在,并且列表理解用于元素迭代的任务。
Python3
# Python3 code to demonstrate working of
# Filter Rows with Range Elements
# Using all() + list comprehension
# initializing list
test_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19],
[2, 5, 10], [2, 3, 4, 5, 6, 7]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 5
# checking for presence of all elements using in operator
res = [sub for sub in test_list if all(ele in sub for ele in range(i, j + 1))]
# printing result
print("Extracted rows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter Rows with Range Elements
# Using filter() + lambda + all()
# initializing list
test_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19],
[2, 5, 10], [2, 3, 4, 5, 6, 7]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 5
# filter() and lambda used to filter elements
res = list(filter(lambda sub: all(
ele in sub for ele in range(i, j + 1)), test_list))
# printing result
print("Extracted rows : " + str(res))
输出:
The original list is : [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]]
Extracted rows : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]]
方法 #2:使用filter() + lambda + all()
在这种情况下,过滤任务是使用 filter() 和 lambda函数完成的,再次使用 all() 来确保所有元素都存在于范围内。
蟒蛇3
# Python3 code to demonstrate working of
# Filter Rows with Range Elements
# Using filter() + lambda + all()
# initializing list
test_list = [[3, 2, 4, 5, 10], [3, 2, 5, 19],
[2, 5, 10], [2, 3, 4, 5, 6, 7]]
# printing original list
print("The original list is : " + str(test_list))
# initializing range
i, j = 2, 5
# filter() and lambda used to filter elements
res = list(filter(lambda sub: all(
ele in sub for ele in range(i, j + 1)), test_list))
# printing result
print("Extracted rows : " + str(res))
输出:
The original list is : [[3, 2, 4, 5, 10], [3, 2, 5, 19], [2, 5, 10], [2, 3, 4, 5, 6, 7]]
Extracted rows : [[3, 2, 4, 5, 10], [2, 3, 4, 5, 6, 7]]