Python|删除嵌套列表中的所有匹配项
删除元素的任务通常不会带来任何挑战,但有时,我们可能会遇到比仅删除单个元素或仅在普通列表中执行删除更复杂的问题。问题可能是删除所有出现的嵌套列表。让我们讨论一些可以解决这个问题的方法。
方法#1:使用列表推导
列表推导可以用作推荐的较长方法的较短方法,以正常的循环方式执行此任务,其中我们只检查匹配并在没有目标列表元素的情况下重建列表。
# Python3 code to demonstrate
# Remove all occurrences in nested list
# using list comprehension
# initializing list
test_list = [[4, 5], [1, 2, 3], [4, 5], [8, 9], [10, 11]]
# initializing list to delete
del_list = [4, 5]
# printing original list
print("The original list : " + str(test_list))
# printing delete list
print("The list to be deleted is : " + str(del_list))
# using list comprehension
# Remove all occurrences in nested list
res = [i for i in test_list if i != del_list]
# print result
print("The list after removal of list element : " + str(res))
输出 :
The original list : [[4, 5], [1, 2, 3], [4, 5], [8, 9], [10, 11]]
The list to be deleted is : [4, 5]
The list after removal of list element : [[1, 2, 3], [8, 9], [10, 11]]
方法 #2:使用filter() + partial() + operator.ne
也可以使用上述功能执行该任务。 filter函数执行过滤,并通过部分函数返回部分列表,并且使用operator.ne
方法施加不相等条件。
# Python3 code to demonstrate
# Remove all occurrences in nested list
# using filter() + partial() + operator.ne
from functools import partial
from operator import ne
# initializing list
test_list = [[4, 5], [1, 2, 3], [4, 5], [8, 9], [10, 11]]
# initializing list to delete
del_list = [4, 5]
# printing original list
print("The original list : " + str(test_list))
# printing delete list
print("The list to be deleted is : " + str(del_list))
# using filter() + partial() + operator.ne
# Remove all occurrences in nested list
res = list(filter(partial(ne, del_list), test_list))
# print result
print("The list after removal of list element : " + str(res))
输出 :
The original list : [[4, 5], [1, 2, 3], [4, 5], [8, 9], [10, 11]]
The list to be deleted is : [4, 5]
The list after removal of list element : [[1, 2, 3], [8, 9], [10, 11]]