Python中list去重且保持原顺序不变的方法

文章目录

  • 乱序
    • list + set
    • fromkeys()
  • 有序
    • list + set + sort
    • for


乱序

list + set

l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
print(l2)

fromkeys()

l1 = ['b','c','d','b','c','a','a']
l2 = {
     }.fromkeys(l1).keys()
print(l2)

有序

list + set + sort

l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
l2.sort(key=l1.index)
print(l2)

另一种写法:

l1 = ['b','c','d','b','c','a','a']
l2 = sorted(set(l1),key=l1.index)
print(l2)

for

l1 = ['b','c','d','b','c','a','a']
l2 = []
for i in l1:
    if i not in l2:
        l2.append(i)
print(l2)

简明写法:

l1 = ['b', 'c', 'd', 'b', 'c', 'a', 'a']
l2 = []
[l2.append(i) for i in l1 if i not in l2]
print(l2)

你可能感兴趣的:(python)