python学习笔记 | 列表去重

'''
@author: 人人都爱小雀斑
@time: 2020/3/10 10:29
@desc:
'''
L=[1,5,7,4,6,3,0,5,8,4,4]

 

方法1:for循环
L1=[]
for i in L:
    if i not in L1:
        L1.append(i)
#L1:[1, 5, 7, 4, 6, 3, 0, 8]


方法2:set函数
L2=set(L)#去重且排序好
#L2:{0, 1, 3, 4, 5, 6, 7, 8}


方法3:利用字典的fromkeys()和keys()方法
d=dict()
L3=list(d.fromkeys(L).keys())
#L3:[1, 5, 7, 4, 6, 3, 0, 8]
# 使用列表的sort函数排序
L3.sort()#L3:[0, 1, 3, 4, 4, 4, 5, 5, 6, 7, 8]
L3.sort(reverse=True)#L3:[8, 7, 6, 5, 5, 4, 4, 4, 3, 1, 0]

  

原文地址:https://www.cnblogs.com/billie52707/p/12454356.html