列表去重的几种方式


1. for 循环去重

list1 = [2, 1, 3, 6, 2, 1]
temp = []
for i in list1:
    if not i in temp:
        temp.append(i)

 

2. 列表推导式去重

list1 = [2, 1, 3, 6, 2, 1]
temp = []
[temp.append(i) for i in list1 if i not in temp]
print(temp)

 

3. set去重

list1 = [2, 1, 3, 6, 2, 1]
temp = list(set(list1))
print(temp)

set去重保持原来的顺序,参考5,6

 

 

4.  使用字典fromkeys()的方法来去重

原理是: 字典的key是不能重复的

list1 = [2, 1, 3, 6, 2, 1]
temp = {}.fromkeys(list1)
print(temp)
print(temp.keys())

 

 

5 . 使用sort + set去重

list1 = [2, 1, 3, 6, 2, 1]
list2 = list(set(list1))
list2.sort(key=list1.index)
print(list2)

 

 

6. 使用sorted+ set函数去重

list1 = [2, 1, 3, 6, 2, 1]
temp = sorted(set(list1), key=list1.index)
print(temp)

 

 

 

删除列表中的重复项

list1 = [2, 1, 3, 6, 2, 1]
temp = [item for item in list1 if list1.count(item) == 1]
print(temp)

 

list1 = [2, 1, 3, 6, 2, 1]
temp = list(filter(lambda x:list1.count(x) ==1, list1))
print(temp)

<filter object at 0x0000022D09697400>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM