从列表中删除所有出现的特定值?

533

在Python中,remove()函数会从列表中移除第一个出现的值。

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

这是我想到的方法:

>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
26个回答

0
你可以将列表转换为numpy.array,然后使用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]

0
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']

可以翻译为:

['h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']


1
请尽量详细解释您的答案。 - parlad

0

我们也可以使用delpop来进行原地删除所有操作:

import random

def remove_values_from_list(lst, target):
    if type(lst) != list:
        return lst

    i = 0
    while i < len(lst):
        if lst[i] == target:
            lst.pop(i)  # length decreased by 1 already
        else:
            i += 1

    return lst

remove_values_from_list(None, 2)
remove_values_from_list([], 2)
remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
lst = remove_values_from_list([random.randrange(0, 10) for x in range(1000000)], 2)
print(len(lst))


现在来谈效率问题:

In [21]: %timeit -n1 -r1 x = random.randrange(0,10)
1 loop, best of 1: 43.5 us per loop

In [22]: %timeit -n1 -r1 lst = [random.randrange(0, 10) for x in range(1000000)]
g1 loop, best of 1: 660 ms per loop

In [23]: %timeit -n1 -r1 lst = remove_values_from_list([random.randrange(0, 10) for x in range(1000000)]
    ...: , random.randrange(0,10))
1 loop, best of 1: 11.5 s per loop

In [27]: %timeit -n1 -r1 x = random.randrange(0,10); lst = [a for a in [random.randrange(0, 10) for x in
    ...:  range(1000000)] if x != a]
1 loop, best of 1: 710 ms per loop

我们可以看到,就地版本的remove_values_from_list()不需要任何额外的内存,但运行时间要长得多:

  • 11秒用于就地删除值
  • 710毫秒用于列表推导式,它在内存中分配了一个新列表

-1

关于速度!

import time
s_time = time.time()

print 'start'
a = range(100000000)
del a[:]
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 3.25

s_time = time.time()
print 'start'
a = range(100000000)
a = []
print 'finished in %0.2f' % (time.time() - s_time)
# start
# finished in 2.11

-3
p=[2,3,4,4,4]
p.clear()
print(p)
[]

只能使用Python 3


3
有趣的是,这符合所提出的问题范围,并且是正确的。 - Erich
我不认为这是正确的。这将从列表中删除所有项目,而不是所有值的出现 - Georgy

-6

这段代码有什么问题:

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

3
请解释一下你的代码行,以便其他用户能够理解其功能。谢谢! - Ignacio Ara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接