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]

posted @   梓涵VV  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 提示词工程——AI应用必不可少的技术
· 地球OL攻略 —— 某应届生求职总结
· 字符编码:从基础到乱码解决
· SpringCloud带你走进微服务的世界
点击右上角即可分享
微信分享提示