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

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

这就是我的想法:

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

当前回答

如果你没有内置过滤器,或者不想使用额外的空间,你需要一个线性解决方案……

def remove_all(A, v):
    k = 0
    n = len(A)
    for i in range(n):
        if A[i] !=  v:
            A[k] = A[i]
            k += 1

    A = A[:k]

其他回答

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

category_ids.sort()
ones_last_index = category_ids.count('1')
del category_ids[0:ones_last_index]

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

从Python列表中删除所有出现的值

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list():
    for list in lists:
      if(list!=7):
         print(list)
remove_values_from_list()

结果:6.9 8.9 3 5 4.9 12.9 9 12.9 10.9 11

另外,

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list(remove):
    for list in lists:
      if(list!=remove):
        print(list)
remove_values_from_list(7)

结果:6.9 8.9 3 5 4.9 12.9 9 12.9 10.9 11

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 ')

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。