去重之后顺序会改变
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]
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]
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]