删除列表的重复元素

一:集合去重(会打乱序列顺序)

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)
list1 =[ 1, 5, 4, 2, 3, 2, 3, 4, 2, 1

猜你喜欢

转载自www.cnblogs.com/li1992/p/9215048.html