列表去重的幾種方式


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