删除列表的重复元素
一:集合去重(会打乱序列顺序)
list1=[1,5,4,2,3,2,3,4,2,1] list2 = list(set(list1)) print(list2)
二:利用字典的fromkey方法去重
list1=[1,5,4,2,3,2,3,4,2,1] list3 = list(dict.fromkeys(list1).keys()) print(list3)
三:for循环去重
list1=[1,5,4,2,3,2,3,4,2,1] tmp = [] for i in list1: if i not in tmp: tmp.append(i) print(tmp)
四:排序去重(会打乱序列顺序)
list1=[1,5,4,2,3,2,3,4,2,1] result_list=[] temp_list=sorted(list1) i=0 while i<len(temp_list): if temp_list[i] not in result_list: result_list.append(temp_list[i]) else: i+=1 print(result_list)
Ideal are like the stars --- we never reach them ,but like mariners , we chart our course by them