无聊统计了下列表去重到底有多少种方法。
1.集合
list(set(alist))
如果要保持顺序:
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.字典
大都是利用哈希表特性
{}.fromkeys(alist).keys()
或者手动写:
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 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.groupby
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)
还有其它方法没?