实现列表去重的几种方法:
myList = [2, 1, 4, 1, 3, 2]
1.set集合去重
newList = list(set(myList))
# newLIst = [1, 2, 3, 4]
注意:使用set去重不会保留原list中元素的顺序
2.遍历列表
newList = []
for i in myList:
if i not in newList:
newList.append(i)
# newList = [2, 1, 4, 3]
列表推导式
newList = []
[newList.append(i) for i in myList if i not in newList]
# newList = [2, 1, 4, 3]
3.sort函数
newList = list(set(oldList))
newList.sort(key=oldList.index)
# newList = [2, 1, 4, 3]
4.sorted函数
newList = sorted(set(myList), key=myList.index)
# newList = [2, 1, 3, 4]