Python中对列表list去重

保留原顺序。

old_list = [2, 3, 4, 5, 1, 2, 3]
new_list = []
for i in old_list:
    if i not in new_list:
        new_list.append(i)
print(new_list) # [2, 3, 4, 5, 1]
  • 用字典dict去重

使用list项作为键创建dict,这将自动删除任何重复项,因为dict不能有重复的键,保留原顺序。

old_list = [2, 3, 4, 5, 1, 2, 3]
new_list = list(dict.fromkeys(old_list))
print(new_list) # [2, 3, 4, 5, 1]
  • 用集合set去重

将list转化为set再转化为list,利用set的自动去重功能,但不保证顺序。

old_list = [2, 3, 4, 5, 1, 2, 3]
new_list = list(set(old_list))
print(new_list) # 不保证顺序:[1, 2, 3, 4, 5]

再加上列表中索引(index)的方法保证去重后的顺序不变。

old_list = [2, 3, 4, 5, 1, 2, 3]
new_list = list(set(old_list))
new_list.sort(key=old_list.index)
print(new_list) # 保留顺序:[2, 3, 4, 5, 1]
posted @   Oops!#  阅读(19)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
历史上的今天:
2018-07-18 zabbix报错listener failed: zbx_tcp_listen() fatal error: unable to serve on any address
2018-07-18 shell脚本中执行mysql 语句,去除warning using a password on the command line interface can be insecure信息
2018-07-18 zabbix_get :command not found 解决办法
2018-07-18 CentOS7 升级到7.4
2018-07-18 jumpserver v0.5.0 创建用户和管理机器
2017-07-18 linux下双网卡的绑定
点击右上角即可分享
微信分享提示