在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]
当前回答
p=[2,3,4,4,4]
p.clear()
print(p)
[]
只有在Python 3中
其他回答
上面所有的答案(除了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
删除所有重复的出现,并在列表中保留一个:
test = [1, 1, 2, 3]
newlist = list(set(test))
print newlist
[1, 2, 3]
下面是我在Project Euler中使用的函数:
def removeOccurrences(e):
return list(set(e))
Numpy方法和对包含1.000.000个元素的列表/数组的计时:
计时:
In [10]: a.shape
Out[10]: (1000000,)
In [13]: len(lst)
Out[13]: 1000000
In [18]: %timeit a[a != 2]
100 loops, best of 3: 2.94 ms per loop
In [19]: %timeit [x for x in lst if x != 2]
10 loops, best of 3: 79.7 ms per loop
结论:numpy(在我的笔记本上)比列表理解方法快27倍
PS如果你想将常规的Python列表lst转换为numpy数组:
arr = np.array(lst)
设置:
import numpy as np
a = np.random.randint(0, 1000, 10**6)
In [10]: a.shape
Out[10]: (1000000,)
In [12]: lst = a.tolist()
In [13]: len(lst)
Out[13]: 1000000
检查:
In [14]: a[a != 2].shape
Out[14]: (998949,)
In [15]: len([x for x in lst if x != 2])
Out[15]: 998949
以可读性为代价,我认为这个版本稍微快一点,因为它不强迫while重新检查列表,因此做完全相同的工作删除必须做的事情:
x = [1, 2, 3, 4, 2, 2, 3]
def remove_values_from_list(the_list, val):
for i in range(the_list.count(val)):
the_list.remove(val)
remove_values_from_list(x, 2)
print(x)
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 ')