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>