Python 在数组/列表中删除所有出现的元素
数组是一组存储在连续内存位置中的同类型元素的集合。Python不提供对内置数组的支持。如果您需要使用数组,您需要导入“array”模块或使用numpy库中的数组。
在Python中,我们可以使用列表代替数组。但是,我们无法限制列表的元素为相同的数据类型。
给定的任务是从数组/列表中删除所有出现的元素,即包括重复的元素。让我们通过考虑一个输入-输出场景来了解这实际上是如何工作的。
输入输出场景
考虑一个由一个或多个重复元素组成的列表。
my_list = [ 1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10 ].
现在,假设我们需要移除元素10。 我们可以清楚地看到元素 10 存在于列表中,并且重复了5次。在删除所有出现的元素后, 结果列表将如下所示 –
my_list = [ 1, 20, 21, 16, 18, 22, 8 ].
从Python列表中删除元素有不同的方法。让我们逐个讨论它们。
使用Remove()方法
在Python中,remove()方法接受一个代表列表中元素的单个值作为参数,并从当前列表中删除它。为了使用这个方法删除所有出现的元素,我们需要将期望的元素与列表中的所有其他元素进行比较,并在匹配发生时调用remove()方法。
示例
在这个示例中,我们将创建一个元素列表,并使用remove()方法删除所有值为10的元素的所有出现。
def removing_elements(my_list, element):
element_count = my_list.count(element)
for i in range(element_count):
my_list.remove(element)
return my_list
if __name__ == "__main__":
my_list = [1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10]
element = 10
print("The list before performing the removal operation is: ")
print(my_list)
result = removing_elements(my_list, element)
print("The list after performing the removal operation is: ")
print(result)
输出
上述程序的输出如下:
The list before performing the removal operation is:
[1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10]
The list after performing the removal operation is:
[1, 20, 21, 16, 18, 22, 8]
使用列表推导式
技术 列表推导式 由复杂的一行语句组成,可以完成整个任务。使用这个技术,当满足给定的基本条件时,可以构建一个新的列表,将其他元素存储起来。
在这里,我们搜索所需的元素,找到后,构建另一个列表,将匹配的元素排除在外。除了匹配的元素之外,其他所有元素都将存储在新构建的列表中,最终被视为结果列表。
示例
让我们看一个示例 –
def removing_elements(my_list, element):
result = [i for i in my_list if i != element]
return result
if __name__ == "__main__":
my_list = [1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10]
element = 10
print("The list before performing the removal operation is: ")
print(my_list)
result = removing_elements(my_list, element)
print("The list after performing the removal operation is: ")
print(result)
输出
上述程序的输出如下:
The list before performing the removal operation is:
[1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10]
The list after performing the removal operation is:
[1, 20, 21, 16, 18, 22, 8]
使用”Filter()”方法
filter()方法接受一个函数和一个可迭代对象作为参数,并根据函数描述的条件过滤给定可迭代对象的元素。
在这里,使用filter()和__ne__
(不等运算符的功能)方法,我们可以过滤与所需元素不相等的列表元素。
示例
在这个示例中,我们通过使用filter()方法来删除列表中所有特定元素的出现。
def removing_elements(my_list, element):
result = list(filter((element).__ne__, my_list))
return result
if __name__ == "__main__":
my_list = [1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10]
element = 10
print("The list before performing the removal operation is: ")
print(my_list)
result = removing_elements(my_list, element)
print("The list after performing the removal operation is: ")
print(result)
输出
以上程序的输出如下:
The list before performing the removal operation is:
[1, 10, 20, 10, 21, 16, 18, 10, 22, 10, 8, 10]
The list after performing the removal operation is:
[1, 20, 21, 16, 18, 22, 8]