無聊統計了下列表去重到底有多少種方法。app
1.集合dom
list(set(alist))
若是要保持順序:blog
import random if __name__=='__main__': a=[random.randint(0,10) for i in xrange(10)] b=list(set(a)) b.sort(key=a.index)
2.字典排序
大都是利用哈希表特性it
{}.fromkeys(alist).keys()
或者手動寫:class
import random if __name__=='__main__': a=[random.randint(0,10) for i in xrange(10)] d={} for i in a: d[i]=1 print d.keys()
3.排序後查重import
import random if __name__=='__main__': a=[random.randint(0,10) for i in xrange(10)] a.sort() print [x for i,x in enumerate(a) if not i or x!=a[i-1]]
4.itertools.groupbylambda
import random import itertools if __name__=='__main__': a=[random.randint(0,10) for i in xrange(10)] a.sort() print [x[0] for x in itertools.groupby(a)]
5.遍歷遍歷
import random if __name__=='__main__': a=[random.randint(0,10) for i in xrange(10)] b=[] for i in a: if i not in b: b.append(i)
或者用reduce:方法
import random import functools if __name__=='__main__': a=[random.randint(0,10) for i in xrange(10)] functools.reduce(lambda x,y:x if y in x else x+[y],[[],]+a)
還有其它方法沒?