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

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

这就是我的想法:

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

当前回答

如果必须修改原始列表,则可以使用切片赋值,同时仍然使用有效的列表理解式(或生成器表达式)。

>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> x[:] = (value for value in x if value != 2)
>>> x
[1, 3, 4, 3]

其他回答

以可读性为代价,我认为这个版本稍微快一点,因为它不强迫while重新检查列表,因此做完全相同的工作删除必须做的事情:

x = [1, 2, 3, 4, 2, 2, 3]
def remove_values_from_list(the_list, val):
    for i in range(the_list.count(val)):
        the_list.remove(val)

remove_values_from_list(x, 2)

print(x)
hello =  ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
#chech every item for a match
for item in range(len(hello)-1):
     if hello[item] == ' ': 
#if there is a match, rebuild the list with the list before the item + the list after the item
         hello = hello[:item] + hello [item + 1:]
print hello

[' h ',‘e’,‘l’,‘l’,‘o’,‘w’,‘o’,‘r’,‘l’,' d ')

以更抽象的方式重复第一篇文章的解决方案:

>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> while 2 in x: x.remove(2)
>>> x
[1, 3, 4, 3]

有什么问题:

Motor=['1','2','2']
for i in Motor:
   if i != '2':
       print(i)
print(motor)

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