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)

猜你喜欢

转载自blog.csdn.net/cunane/article/details/82154106