""" l1 = [11, 2, 3, 22, 2, 4, 11, 3] 去重并保持原来的顺序 """
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#方式一 for 循环方法 l1 = [11, 2, 3, 22, 2, 4, 11, 3] l2 = [] for i in l1: if i not in l2: l2.append(i) print(l2) #方式二 l3 = list(set(l1)) # 将列表用set去重,再转换回列表(没有按照之前的顺序) l3.sort(key=l1.index) # 将上一步得到的列表排序,按照l1中的顺序排序 print(l3)
#有同学可能不懂key,key就是一个排序的依据 #在匿名函数中也是这么运用的看下面例子 l4 = [ {"name": "大娃", "age": 38}, {"name": "二娃", "age": 18}, {"name": "三娃", "age": 19}, {"name": "四娃", "age": 29}, {"name": "五娃", "age": 30}, ] l4.sort(key=lambda x: x['age']) print(l4) #实质就是 def tmp(x): # 返回一个排序的依据 {"name": "大娃", "age": 38}, return x["age"] l4.sort(key=tmp) print(l4)