Python对list中元素去重的方法(包括原序去重)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/JohinieLi/article/details/81182771

笔者小白在日常中遇到了需要对list列表中的元素去重的情况,根据相关资料整理,现将python中的一些方法归纳如下:

1、遍历

先建立一个新的空列表,通过遍历原来的列表,再利用逻辑关系not in 来去重。
这样可以做出来,但是过程不够简单。不过此方法保证了列表的顺序性。

li=[1,2,3,4,5,1,2,3]
new_li=[]
for i in li:
    if i not in new_li:
    new_li.append(i)
print(new_li)

2、利用set

将列表转化为集合再转化为列表,利用集合的自动去重功能。简单快速。缺点是:使用set方法无法保证去重后的顺序。

li=[1,2,3,4,5,1,2,3]
li=list(set(li))
print(li)

3、利用set+索引

可以通过列表中索引(index)的方法保证去重后的顺序不变。

li=[1,2,3,4,5,1,2,3]
new_li=list(set(li))
new_li.sort(key=li.index)
print(new_li)

4、使用keys()

但是结果不能保持原来的顺序

li = [1,0,3,7,7,5]
formatList = list({}.fromkeys(li).keys())
print (formatList)

5、使用itertools.grouby

import itertools
ids = [1,4,3,3,4,2,3,4,5,6,1]
ids.sort()
it = itertools.groupby(ids)
for k, g in it:
    print k

关于的itertools.groupby的原理介绍参考1itertools.groupby的原理参考2

6、用reduce

思路其实就是先把ids变为[[], 1,4,3,……] ,然后在利用reduce的特性。这里的去重不会改变原来的顺序。

ids = [1,4,3,3,4,2,3,4,5,6,1]
func = lambda x,y:x if y in x else x + [y]
reduce(func, [[], ] + ids)

Out: [1, 4, 3, 2, 5, 6]

关于lambda的介绍,关于reduce的参考1参考2

参考资料:
1、https://www.cnblogs.com/tianyiliang/p/7845932.html 2018.7.24
2、https://www.jb51.net/article/129759.htm 2018.7.24
3、https://blog.csdn.net/hugo2052/article/details/78494411 2018.7.24
4、https://www.cnblogs.com/nyist-xsk/p/7473236.html 2018.7.24

猜你喜欢

转载自blog.csdn.net/JohinieLi/article/details/81182771
今日推荐