在Python中remove()将删除列表中第一个出现的值。
如何从列表中删除一个值的所有出现?
这就是我的想法:
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
在Python中remove()将删除列表中第一个出现的值。
如何从列表中删除一个值的所有出现?
这就是我的想法:
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
当前回答
没有人给出时间和空间复杂性的最佳答案,所以我想试试。下面是一种解决方案,它可以在不创建新数组的情况下删除所有特定值的出现,并且具有有效的时间复杂度。缺点是元素不能维持秩序。
时间复杂度:O(n) 额外空间复杂度:O(1)
def main():
test_case([1, 2, 3, 4, 2, 2, 3], 2) # [1, 3, 3, 4]
test_case([3, 3, 3], 3) # []
test_case([1, 1, 1], 3) # [1, 1, 1]
def test_case(test_val, remove_val):
remove_element_in_place(test_val, remove_val)
print(test_val)
def remove_element_in_place(my_list, remove_value):
length_my_list = len(my_list)
swap_idx = length_my_list - 1
for idx in range(length_my_list - 1, -1, -1):
if my_list[idx] == remove_value:
my_list[idx], my_list[swap_idx] = my_list[swap_idx], my_list[idx]
swap_idx -= 1
for pop_idx in range(length_my_list - swap_idx - 1):
my_list.pop() # O(1) operation
if __name__ == '__main__':
main()
其他回答
很多答案都很好。如果你是python初学者,这里有一个简单的方法,以防你肯定想使用remove()方法。
rawlist = [8, 1, 8, 5, 8, 2, 8, 9, 8, 4]
ele_remove = 8
for el in rawlist:
if el == ele_remove:
rawlist.remove(ele_remove)
对于太大的列表,它可能会慢一些。
如果必须修改原始列表,则可以使用切片赋值,同时仍然使用有效的列表理解式(或生成器表达式)。
>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> x[:] = (value for value in x if value != 2)
>>> x
[1, 3, 4, 3]
Let
>>> x = [1, 2, 3, 4, 2, 2, 3]
最简单有效的解决方案是
>>> x[:] = [v for v in x if v != 2]
>>> x
[1, 3, 4, 3]
另一种使用较少内存但速度较慢的方法是
>>> for i in range(len(x) - 1, -1, -1):
if x[i] == 2:
x.pop(i) # takes time ~ len(x) - i
>>> x
[1, 3, 4, 3]
长度为1000和100000且有10%匹配条目的列表的计时结果:0.16 vs 0.25 ms, 23 vs 123 ms。
您可以将列表转换为numpy。数组,然后使用np.delete并传递该元素及其所有出现的元素的索引。
import numpy as np
my_list = [1, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7]
element_to_remove = 3
my_array = np.array(my_list)
indices = np.where(my_array == element_to_remove)
my_array = np.delete(my_array, indices)
my_list = my_array.tolist()
print(my_list)
#output
[1, 2, 4, 5, 6, 7, 4, 5, 6, 7]
如果你的列表只包含一个元素的副本,例如list_a=[0,0,0,0,0,0,1,3,4,6,7],下面的代码将是有帮助的:
list_a=[0,0,0,0,0,0,1,3,4,6,7]
def remove_element(element,the_list):
the_list=list(set(the_list))
the_list.remove(element)
return the_list
list_a=remove_element(element=0,the_list=list_a)
print(list_a)
or
a=list(set(i for i in list_a if i!=2))
a.remove(2)
基本思想是集合不允许重复,因此首先我将列表转换为set(删除重复项),然后使用.remove()函数删除元素的第一个实例(因为现在每个项只有一个实例)。
但如果你有多个元素的副本,下面的方法会有帮助:
列表理解
list_a=[1, 2, 3, 4, 2, 2, 3]
remove_element=lambda element,the_list:[i for i in the_list if i!=element]
print(remove_element(element=2,the_list=list_a))
过滤器
list_a=[1, 2, 3, 4, 2, 2, 3]
a=list(filter(lambda a: a != 2, list_a))
print(a)
While循环
list_a=[1, 2, 3, 4, 2, 2, 3]
def remove_element(element,the_list):
while element in the_list:the_list.remove(element)
return the_list
print(remove_element(2,list_a))
for循环(与列表推导式相同)
list_a=[1, 2, 3, 4, 2, 2, 3]
a=[]
for i in list_a:
if i!=2:
a.append(i)
print(a)