这有好几种方法实现。
使用set实现
def unique_everseen(items):
seen = set()
seen_add = seen.add
return [x for x in items if not (x in seen or seen_add(x))]
函数里把seen.add赋值给seen_add本地变量是出于性能考虑,因为seen会动态变化,如果直接在迭代里调用它会导致python每次都需要对它做检查。
more_itertools内置的unique_everseen函数
安装more_itertools
pip install more_itertools
使用
>>> from more_itertools import unique_everseen
>>> items = [1, 2, 0, 1, 3, 2]
>>> list(unique_everseen(items))
[1, 2, 0, 3]
OrderedDict
>>> from collections import OrderedDict
>>> items = [1, 2, 0, 1, 3, 2]
>>> list(OrderedDict.fromkeys(items))
[1, 2, 0, 3]