Python中对列表list去重
1、自己写脚本去重
new_list=[] for i in array: if i not in new_list: new_list.append(i)
2、用集合set去重
先转为集合去重,再转为list
a=[2,3,4,1,2,3,4] set(a) {1, 2, 3, 4} list(set(a)) [1, 2, 3, 4]
再加上列表中索引(index)的方法保证去重后的顺序不变
a=[2,3,4,1,2,3,4]
b=list(set(a)) b [1, 2, 3, 4] b.sort(key=a.index) b [2, 3, 4, 1]
3、用字典dict去重
list项作为键创建dict,将会去除重复的项,因为dict key不能重复
old_list = [2, 3, 4, 5, 1, 2, 3] new_list = list(dict.fromkeys(old_list)) print(new_list) # [2, 3, 4, 5, 1]