一重列表
1、使用set,结果会乱序
List = [3,3,2,4,4,5]
NewList = list(set(List))
print (NewList)#结果:[2, 3, 4, 5]
2、使用字典fromkeys()和keys()方法,结果会乱序
让列表作为字典的key,然后取出所有key
List = [3,3,2,4,4,5]
NewList = list({}.fromkeys(List).keys())
print (NewList)#结果:[3, 2, 4, 5]
- 循环遍历法
List = [3,3,2,4,4,5]
NewList = []
for id in List:
if id not in NewList:
NewList.append(id)
print (NewList)#结果:[3, 2, 4, 5]
- 方法1按照索引再次排序
List = [3,3,2,4,4,5]
NewList = list(set(List))
NewList.sort(key=List.index)#List.index是一个函数
print (NewList)#结果:[1, 0, 3, 7, 5]
多重列表去重,set不行,改用下面方法
List = [[1, 2, 3], [2, 2, 3], [2, 2, 3]]
NewList = list(set(tuple(i) for i in List))#转化为元组做主键
print (NewList)#结果[(2, 2, 3), (1, 2, 3)]
NewList = [list(t) for t in set(tuple(i) for i in List)]
print (NewList)#结果[[2, 2, 3], [1, 2, 3]]
NewList.sort(key=List.index)
print (NewList)#结果[[1, 2, 3], [2, 2, 3]]