Python列表去重

實現列表去重的幾種方法:
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]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章