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

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

这就是我的想法:

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

当前回答

您可以将列表转换为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]

其他回答

如果你不关心列表的顺序,如果你关心最终的顺序,我相信这可能比其他任何方法都快。

category_ids.sort()
ones_last_index = category_ids.count('1')
del category_ids[0:ones_last_index]
for i in range(a.count(' ')):
    a.remove(' ')

我相信要简单得多。

很多答案都很好。如果你是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]
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 ')