使用自定义列表元素删除行的Python程序
给定一个矩阵,这里的任务是编写一个Python程序,从自定义列表中删除包含任何元素的行,然后显示结果。
例子:
Input : test_list = [[5, 3, 1], [7, 8, 9], [1, 10, 22], [12, 18, 21]], check_list = [3, 10, 19, 29, 20, 15]
Output : [[7, 8, 9], [12, 18, 21]]
Explanation : [5, 3, 1] row has 3 in it in custom list, hence omitted.
Input : test_list = [[5, 3, 1], [7, 8, 19], [1, 10, 22], [12, 18, 20]], check_list = [3, 10, 19, 29, 20, 15]
Output : []
Explanation : All rows have some element from custom list, hence omitted.
方法 1:使用 any() 和列表推导式
在这里,我们执行检查自定义列表中的任何元素以使用 any() 检查行的任务,如果在行中找到自定义列表中的任何元素,则使用列表理解来省略行。
例子:
Python3
# initializing Matrix
test_list = [[5, 3, 1], [7, 8, 9], [1, 10, 22], [12, 18, 21]]
# printing original list
print("The original list is : " + str(test_list))
# initializing custom list
check_list = [3, 10, 19, 29, 20, 15]
# list comprehension used to omit rows from matrix
# any() checks for any element found from check list
res = [row for row in test_list if not any(el in row for el in check_list)]
# printing result
print("The omitted rows matrix : " + str(res))
Python3
# initializing Matrix
test_list = [[5, 3, 1], [7, 8, 9], [1, 10, 22], [12, 18, 21]]
# printing original list
print("The original list is : " + str(test_list))
# initializing custom list
check_list = [3, 10, 19, 29, 20, 15]
# filter() used to perform filtering
# any() checks for any element found from check list
res = list(filter(lambda row: not any(
el in row for el in check_list), test_list))
# printing result
print("The omitted rows matrix : " + str(res))
输出:
The original list is : [[5, 3, 1], [7, 8, 9], [1, 10, 22], [12, 18, 21]]
The omitted rows matrix : [[7, 8, 9], [12, 18, 21]]
方法 2:使用 filter()、lambda 和 any()
与上述方法类似,唯一不同的是 filter() 和 lambda函数用于执行从结果中过滤出或省略矩阵中的行的任务。
例子:
蟒蛇3
# initializing Matrix
test_list = [[5, 3, 1], [7, 8, 9], [1, 10, 22], [12, 18, 21]]
# printing original list
print("The original list is : " + str(test_list))
# initializing custom list
check_list = [3, 10, 19, 29, 20, 15]
# filter() used to perform filtering
# any() checks for any element found from check list
res = list(filter(lambda row: not any(
el in row for el in check_list), test_list))
# printing result
print("The omitted rows matrix : " + str(res))
输出:
The original list is : [[5, 3, 1], [7, 8, 9], [1, 10, 22], [12, 18, 21]]
The omitted rows matrix : [[7, 8, 9], [12, 18, 21]]