标签:app 建立 reduce lis lse 删除 imp print not
怎么快速的对列表进行去重呢,去重之后原来的顺序会不会改变呢?
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]
标签:app 建立 reduce lis lse 删除 imp print not
原文地址:https://www.cnblogs.com/xxpythonxx/p/12181224.html