1. 程式人生 > >Python 列表中每個元素只保留一份

Python 列表中每個元素只保留一份

摘自《Think Python》練習10-9:

編寫一個函式remove_duplicates,接收一個列表,並返回一個新列表,其中只包含原始列表的每個元素的唯一一份。

提示:它們不需要順序相同

方法1:按原順序

def remove_duplicates_1(l):
    newlist = []
    for s in l:
        if s not in newlist:
            newlist.append(s)
    return newlist

方法2:不按原順序

def remove_duplicates_2(l):
    return list(set(l))

方法3:按原順序 【推薦】

def remove_duplicates_3(l):
    return sorted(set(l),key = l.index)