1. 程式人生 > >Python列表去重複元素

Python列表去重複元素

比較容易記憶的是用內建的set

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

還有一種據說速度更快的,沒測試過兩者的速度差別

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

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

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

如果想要保持他們原來的排序:

用list類的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

也可以用遍歷

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']