列表去重的多种方法
python中列表去重
怎么快速的对列表进行去重呢,去重之后原来的顺序会不会改变呢?
去重之后顺序会改变
set去重
#列表去重改变原列表的顺序了 l1 = [1,4,4,2,3,4,5,6,1] l2 = list(set(l1)) print(l2) # [1, 2, 3, 4, 5, 6]
但是,可以通过列表中索引(index)的方法保证去重后的顺序不变。
l1 = [1,4,4,2,3,4,5,6,1] l2 = list(set(l1)) l2.sort(key=l1.index) print(l2) # [1, 4, 2, 3, 5, 6]
itertools.groupby
import itertools l1 = [1,4,4,2,3,4,5,6,1] l1.sort() l = [] it = itertools.groupby(l1) for k,g in it: l.append(k) print(l) # [1, 2, 3, 4, 5, 6]
fromkeys
l1 = [1,4,4,2,3,4,5,6,1] t = list({}.fromkeys(l1).keys()) # 解决顺序问题 t.sort(key=l1.index) print(t) # [1, 4, 2, 3, 5, 6]
通过删除索引
l1 = [1,4,4,2,3,4,5,6,1] t = l1[:] for i in l1: while t.count(i) >1: del t[t.index(i)] # 解决顺序问题 t.sort(key=l1.index) print(t) # [1, 4, 2, 3, 5, 6]
去重不改变顺序
建立新列表[]
l1 = [1,4,4,2,3,4,5,6,1] new_l1 = [] for i in l1: if i not in new_l1: new_l1.append(i) print(new_l1) # [1, 4, 2, 3, 5, 6]
reduce方法
from functools import reduce l1 = [1,4,4,2,3,4,5,6,1] func = lambda x,y:x if y in x else x + [y] print(reduce(func,[[],]+l1)) # [1, 4, 2, 3, 5, 6]