在Python中,remove()
函数会从列表中移除第一个出现的值。
如何从列表中删除所有出现的值?
这是我想到的方法:
>>> remove_values_from_list([1, 2, 3, 4, 2, 2, 3], 2)
[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]
或者>>> x = [1,2,3,2,2,2,3,4]
>>> list(filter(lambda a: a != 2, x))
[1, 3, 3, 4]
或者>>> [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]
你可以使用列表推导式:
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]
in
运算符还是remove
方法都会扫描整个列表(直到找到匹配项),因此你最终会以这种方式多次扫描列表。 - John Kugelman如果原始列表必须被修改,你可以使用切片赋值,同时仍然使用高效的列表推导或生成器表达式。
>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> x[:] = (value for value in x if value != 2)
>>> x
[1, 3, 4, 3]
以更抽象的方式重复第一篇帖子的解决方案:
>>> x = [1, 2, 3, 4, 2, 2, 3]
>>> while 2 in x: x.remove(2)
>>> x
[1, 3, 4, 3]
x = [1] * 10000 + [2] * 1000
。循环体执行1000次,并且每次调用 .remove()
都要跳过10000个元素。这似乎是 O(n*n) 的,但没有证据。我认为证明的方法是假设列表中数字2的数量与其长度成比例。这个比例因子在大O符号中消失了。然而,如果列表中只有常数个2,则最好的情况不是 O(n^2),而只是O(2n),它是O(n)。 - Hannes看看这个简单的解决方案
>>> [i for i in x if i != 2]
这将返回一个列表,其中包含所有没有2
的x
元素。
x = [i for i in x if i!=2]
>>> 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
>>> def removeall_replace(x, l):
.... t = [y for y in l if y != x]
.... del l[:]
.... l.extend(t)
def remove_all(x, l): return [y for y in l if y != x]
然后 l = remove_all(3,l)
- DannidNumpy方法对比一个包含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倍。
附注:如果你想将你的常规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
a = [1, 2, 2, 3, 1]
to_remove = 1
a = [i for i in a if i != to_remove]
print(a)
要删除所有重复的出现并在列表中留下一个:
test = [1, 1, 2, 3]
newlist = list(set(test))
print newlist
[1, 2, 3]
这是我在欧拉计划中使用的函数:
def removeOccurrences(e):
return list(set(e))
[y for y in x if y != 2]
。 - coredumperror__ne__
会得到-1。将两个值进行比较远比只在其中一个上调用__eq__
或__ne__
复杂得多。尽管在这里可能因为你只比较数字而正确工作,但在一般情况下却是错误的并且是个bug。 - Aran-Fey