在Python中remove()将删除列表中第一个出现的值。

如何从列表中删除一个值的所有出现?

这就是我的想法:

>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]

当前回答

a = [1, 2, 2, 3, 1]
to_remove = 1
a = [i for i in a if i != to_remove]
print(a)

也许不是最蟒蛇的,但对我来说仍然是最简单的,哈哈

其他回答

如果你的列表只包含一个元素的副本,例如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)

我只是做了一个列表。我只是个初学者。稍微高级一点的程序员当然可以写出这样的函数。

for i in range(len(spam)):
    spam.remove('cat')
    if 'cat' not in spam:
         print('All instances of ' + 'cat ' + 'have been removed')
         break

Numpy方法和对包含1.000.000个元素的列表/数组的计时:

计时:

In [10]: a.shape
Out[10]: (1000000,)

In [13]: len(lst)
Out[13]: 1000000

In [18]: %timeit a[a != 2]
100 loops, best of 3: 2.94 ms per loop

In [19]: %timeit [x for x in lst if x != 2]
10 loops, best of 3: 79.7 ms per loop

结论:numpy(在我的笔记本上)比列表理解方法快27倍

PS如果你想将常规的Python列表lst转换为numpy数组:

arr = np.array(lst)

设置:

import numpy as np
a = np.random.randint(0, 1000, 10**6)

In [10]: a.shape
Out[10]: (1000000,)

In [12]: lst = a.tolist()

In [13]: len(lst)
Out[13]: 1000000

检查:

In [14]: a[a != 2].shape
Out[14]: (998949,)

In [15]: len([x for x in lst if x != 2])
Out[15]: 998949
p=[2,3,4,4,4]
p.clear()
print(p)
[]

只有在Python 3中

for i in range(a.count(' ')):
    a.remove(' ')

我相信要简单得多。