Python|从列表列表中删除给定元素
从列表中删除基本元素已经被处理过很多次了,但有时我们不仅仅是一个列表,我们有一个列表列表,我们需要在其中执行这个特定的任务。使用速记来执行此特定任务会有所帮助。让我们讨论执行此特定任务的某些方法。
方法#1:使用列表推导
这种方法背后的逻辑是减少代码的大小并使用循环作为列表理解本身的一种方式来执行任务。
# Python3 code to demonstrate
# Removing element from list of lists
# using list comprehension
# initializing list
test_list = [[4, 5, 6], [5, 6, 4, 1], [4], [4, 8, 9, 10]]
# printing original list
print("The original list : " + str(test_list))
# initializing Number to delete
N = 4
# using list comprehension
# Removing element from list of lists
res = [[ele for ele in sub if ele != N] for sub in test_list]
# print result
print("The list after deletion of element : " + str(res))
输出 :
The original list : [[4, 5, 6], [5, 6, 4, 1], [4], [4, 8, 9, 10]]
The list after deletion of element : [[5, 6], [5, 6, 1], [], [8, 9, 10]]
方法2:使用列表理解+列表切片
在这个方法中,我们一般做的任务和上面的方法类似,只是我们使用列表切片来提高代码的可读性。
# Python3 code to demonstrate
# Removing element from list of lists
# using list comprehension + list slicing
# initializing list
test_list = [[4, 5, 6], [5, 6, 4, 1], [4], [4, 8, 9, 10]]
# printing original list
print("The original list : " + str(test_list))
# initializing Number to delete
N = 4
# using list comprehension + list slicing
# Removing element from list of lists
for sub in test_list:
sub[:] = [ele for ele in sub if ele != N]
# print result
print("The list after deletion of element : " + str(test_list))
输出 :
The original list : [[4, 5, 6], [5, 6, 4, 1], [4], [4, 8, 9, 10]]
The list after deletion of element : [[5, 6], [5, 6, 1], [], [8, 9, 10]]