使用尽可能多的方法实现list去重
ls=[1,22,3,4,52,2,3,3,3,42,2,4,45,6]
1.利用set
print(list(set(ls)))
2 新生成一个列表,通过循环判断插入
ls1=[]
for i in ls:
if i not in ls1:
ls1.append(i)
print("循环新列表:%s"%ls1)
3.字典的方式
d = {}
print(d.fromkeys(ls).keys())
4 函数defaultdict
from collections import defaultdict
a=defaultdict()
for i in ls:
a[i]=0
print("利用defaultdict:%s"%a.keys())
5 利用itertools的groupby(参考他人)
from itertools import groupby
ls.sort()
new_groupby=groupby(ls)
new_ls=[]
for k,v in new_groupby:
new_ls.append(k)
print("利用itertools的groupby方法:%s"%new_ls)
6.reduce方法(python3需要从functools导入reduce)
from functools import reduce
print(reduce(lambda k,v:k if v in k else k + [v], [[],] + ls))