摘自《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)
博客围绕Python列表去重展开,源于《Think Python》练习10 - 9。介绍了编写函数remove_duplicates接收列表并返回无重复元素新列表的需求,给出三种方法,分别是按原顺序、不按原顺序和按原顺序(推荐),还提及可参考Python官方文档。

646

被折叠的 条评论
为什么被折叠?



