Python list中去重的多种方法

2021/7/3 12:51:28

本文主要是介绍Python list中去重的多种方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

去重之后顺序会改变

set去重 (列表去重会让列表改变原来的顺序)

l1 = [1,4,4,2,3,4,5,6,1]
l2 = list(set(l1))
print(l2)    # [1, 2, 3, 4, 5, 6]

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

l1 = [1,4,4,2,3,4,5,6,1]
l2 = list(set(l1))
l2.sort(key=l1.index)
print(l2)      # [1, 4, 2, 3, 5, 6]
itertools.groupby

itertools.groupby

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

fromkeys

l1 = [1,4,4,2,3,4,5,6,1]
t = list({}.fromkeys(l1).keys())
# 解决顺序问题
t.sort(key=l1.index)
print(t)         # [1, 4, 2, 3, 5, 6]

通过删除索引

l1 = [1,4,4,2,3,4,5,6,1]
t = l1[:]
for i in l1:
    while t.count(i) >1:
          del t[t.index(i)]
# 解决顺序问题
t.sort(key=l1.index)
print(t)    # [1, 4, 2, 3, 5, 6]

去重不改变顺序

建立新列表[]

l1 = [1,4,4,2,3,4,5,6,1]
new_l1 = []
for i in l1:
    if i not in new_l1:
        new_l1.append(i)
print(new_l1)    # [1, 4, 2, 3, 5, 6]

reduce方法

from functools import reduce
l1 = [1,4,4,2,3,4,5,6,1]
func = lambda x,y:x if y in x else x + [y]
print(reduce(func,[[],]+l1))   # [1, 4, 2, 3, 5, 6]

 



这篇关于Python list中去重的多种方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程