一以贯之

列表去重的几种方式

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>

 

posted on 2019-05-21 14:05  凡夫or俗子  阅读(10857)  评论(0)    收藏  举报