在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]

其他回答

你可以使用列表推导式:

def remove_values_from_list(the_list, val):
   return [value for value in the_list if value != val]

x = [1, 2, 3, 4, 2, 2, 3]
x = remove_values_from_list(x, 2)
print x
# [1, 3, 4, 3]

功能的方法:

Python 3. x

>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter((2).__ne__, x))
[1, 3, 3, 4]

or

>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter(lambda a: a != 2, x))
[1, 3, 3, 4]

or

>>> [i for i in x if i != 2]

Python 2. x

>>> x = [1,2,3,2,2,2,3,4]
>>> filter(lambda a: a != 2, x)
[1, 3, 3, 4]

参见简单的解决方案

>>> [i for i in x if i != 2]

这将返回一个包含x的所有元素的列表,没有2

从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

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