Python 去除列表中重複的元素

來自比較容易記憶的是用內置的setapp

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

還有一種聽說速度更快的,沒測試過二者的速度差異.net

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

這兩種都有個缺點,祛除重複元素後排序變了:排序

['a', 'c', 'b', 'd']get

若是想要保持他們原來的排序:遍歷

用list類的sort方法方法

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

也能夠這樣寫index

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

也能夠用遍歷

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

上面的代碼也能夠這樣寫

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

這樣就能夠保證排序不變了:

['b', 'c', 'd', 'a']

相關文章
相關標籤/搜索