Python列表去重
1. 使用set(),是一个无序不重复元素集(重新排序)
inList = [55,21,0,3,17,17,5] outList = list(set(inList)) print (outList)
结果:
[0,3,5,17,21,55]
2. 使用keys()方法(重新排序)
inList = [55,21,0,3,17,17,5]
outList = list({}.fromkeys(inList).keys())
print (outList)
结果:
[0,3,5,17,21,55]
3. 循环遍历法(保持排序)
orgList = [55,21,0,3,17,17,5] formatList = [] for id in orgList: if id not in formatList: formatList.append(id) print (formatList)
结果:
[55,21,0,3,17,5]
4. 按照索引再次排序(保持排序)
orgList = [55,21,0,3,17,17,5] formatList = list(set(orgList)) formatList.sort(key=orgList.index) print (formatList)
结果:
[55,21,0,3,17,5]