1.利用集合去重
def deduplicate(items):
return list(set(items))
2.利用空列表
def deduplicate(items):
result = []
for item in items:
if item not in result:
result.append(item)
return result
3.利用字典的fromkeys
def deduplicate(items):
return {}.fromkeys(items).keys()
4.利用reduce函数
def deduplicate(items):
from functools import reduce
return list(reduce(lambda x, y: x if y in x else x+[y], items, []))
5.利用sorted函数
def deduplicate(items):
return sorted(list(set(items)), key=items.index)
6.利用groupby函数
def deduplicate(items):
from itertools import groupby
items.sort()
tem_res = groupby(items)
result = []
for x, y in tem_res:
result.append(x)
return result
7.基本方法
def deduplicate(items):
for i in range(len(items) - 1, -1, -1):
for j in range(i - 1, -1, -1):
if items[i] == items[j]:
items.pop(i)
break
return items
网友评论