實現列表去重的幾種方法:
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]