<分区>
我遇到了很多任务,在这些任务中我需要过滤 python (2.7) 列表以仅保留有序的唯一值。我常用的方法是使用集合中的 odereddict
:
from collections import OrderedDict
ls = [1,2,3,4,1,23,4,12,3,41]
ls = OrderedDict(zip(ls,['']*len(ls))).keys()
print ls
输出是:
[1, 2, 3, 4, 23, 12, 41]
有没有其他最先进的方法可以在 Python 中做到这一点?
- 注意 - 输入和输出应作为
list
编辑 - 可以在此处找到方法的比较: https://www.peterbe.com/plog/uniqifiers-benchmark
同时最好的解决方案是:
def get_unique(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]