在Python中remove()将删除列表中第一个出现的值。
如何从列表中删除一个值的所有出现?
这就是我的想法:
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[1, 3, 4, 3]
在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]
其他回答
我只是做了一个列表。我只是个初学者。稍微高级一点的程序员当然可以写出这样的函数。
for i in range(len(spam)):
spam.remove('cat')
if 'cat' not in spam:
print('All instances of ' + 'cat ' + 'have been removed')
break
你可以使用列表推导式:
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]
for i in range(a.count(' ')):
a.remove(' ')
我相信要简单得多。
上面所有的答案(除了Martin Andersson的)都创建了一个没有所需项目的新列表,而不是从原始列表中删除项目。
>>> import random, timeit
>>> a = list(range(5)) * 1000
>>> random.shuffle(a)
>>> b = a
>>> print(b is a)
True
>>> b = [x for x in b if x != 0]
>>> print(b is a)
False
>>> b.count(0)
0
>>> a.count(0)
1000
>>> b = a
>>> b = filter(lambda a: a != 2, x)
>>> print(b is a)
False
如果您有对列表的其他引用,这可能很重要。
要就地修改列表,可以使用如下方法
>>> def removeall_inplace(x, l):
... for _ in xrange(l.count(x)):
... l.remove(x)
...
>>> removeall_inplace(0, b)
>>> b is a
True
>>> a.count(0)
0
就速度而言,我笔记本电脑上的结果是(全部在5000个条目列表中,删除了1000个条目)
列表理解- ~400us 过滤器- ~900us .remove()循环- 50ms
因此.remove循环大约要慢100倍........嗯,也许需要一种不同的方法。我发现最快的方法是使用列表理解,但随后替换原始列表的内容。
>>> def removeall_replace(x, l):
.... t = [y for y in l if y != x]
.... del l[:]
.... l.extend(t)
Removeall_replace () - 450us
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 ')