过滤列表

Hel*_*nar 4 python list unique

我想过滤列表中的重复元素

foo = ['a','b','c','a','b','d','a','d']
Run Code Online (Sandbox Code Playgroud)

我只对以下内容感兴趣:

['a','b','c','d']
Run Code Online (Sandbox Code Playgroud)

实现这一目标的有效方法是什么?干杯

sc4*_*c45 21

list(set(foo)) 如果您使用的是Python 2.5或更高版本,但这不保持顺序.


Jus*_* R. 12

如果您不关心元素顺序,请将foo转换为集合.


Mar*_*off 5

由于没有列表理解的订单保留答案,我提出以下建议:

>>> temp = set()
>>> [c for c in foo if c not in temp and (temp.add(c) or True)]
['a', 'b', 'c', 'd']
Run Code Online (Sandbox Code Playgroud)

也可以写成

>>> temp = set()
>>> filter(lambda c: c not in temp and (temp.add(c) or True), foo)
['a', 'b', 'c', 'd']
Run Code Online (Sandbox Code Playgroud)

根据所包含的元素数量foo,您可以通过重复哈希查找而不是通过临时列表重复迭代搜索来获得更快的结果.

c not in temp验证temp没有项目c; 当项目添加到集合时,or True部件强制c要发送到输出列表.