Python對列表去重的4種方法

pythontab發表於2017-12-04

開發中對陣列、列表去重是非常常見的需求,對一個list中的id進行去重,有下面幾種方法,前面兩種方法不能保證順序, 後面兩種方法可以保持原來的順序。

下面的程式碼都在Python3下測試透過, Python2下請自行測試

1. 使用set的特型,python的set和其他語言類似, 是一個無序不重複元素集

orgList = [1,0,3,7,7,5]
#list()方法是把字串str或元組轉成陣列
formatList = list(set(orgList))
print (formatList)

結果:

[0, 1, 3, 5, 7]


2. 使用keys()方法

orgList = [1,0,3,7,7,5]
#list()方法是把字串str或元組轉成陣列
formatList = list({}.fromkeys(orgList).keys())
print (formatList)

結果:

[0, 1, 3, 5, 7]


上面兩種方法的問題是:結果是沒有保持原來的順序。


3. 迴圈遍歷法

orgList = [1,0,3,7,7,5]
formatList = []
for id in orgList:
    if id not in formatList:
        formatList.append(id)
print (formatList)

結果:

[1, 0, 3, 7, 5]

but,這樣的程式碼不夠簡潔,不夠高階


4. 按照索引再次排序

orgList = [1,0,3,7,7,5]
formatList = list(set(orgList))
formatList.sort(key=orgList.index)
print (formatList)

結果:

[1, 0, 3, 7, 5]


相關文章