Python对列表去重的多种方法(四种方法)
作者:mrr 时间:2023-03-18 23:38:19
无聊统计了下列表去重到底有多少种方法。下面小编给大家总结一下,具体内容详情如下;
开发中对数组、列表去重是非常常见的需求,对一个list中的id进行去重,有下面几种方法,前面两种方法不能保证顺序, 后面两种方法可以保持原来的顺序。
下面的代码都在Python3下测试通过, Python2下请自行测试
1. 使用set的特型,python的set和其他语言类似, 是一个无序不重复元素集
orgList = [1,0,3,7,7,5]
#list()方法是把字符串str或元组转成数组
formatList = list(set(orgList))
print (formatList)
结果:
[0, 1, 3, 5, 7]
2. 使用keys()方法
orgList = [1,0,3,7,7,5]
#list()方法是把字符串str或元组转成数组
formatList = list({}.fromkeys(orgList).keys())
print (formatList)
结果:
[0, 1, 3, 5, 7]
上面两种方法的问题是:结果是没有保持原来的顺序。
3. 循环遍历法
orgList = [1,0,3,7,7,5]
formatList = []
for id in orgList:
if id not in formatList:
formatList.append(id)
print (formatList)
结果:
[1, 0, 3, 7, 5]
but,这样的代码不够简洁,不够高端
4. 按照索引再次排序
orgList = [1,0,3,7,7,5]
formatList = list(set(orgList))
formatList.sort(key=orgList.index)
print (formatList)
结果:
[1, 0, 3, 7, 5]
总结
以上所述是小编给大家介绍的Python对列表去重的多种方法(四种方法)网站的支持!
来源:http://www.pythontab.com/html/2017/pythonjichu_1204/1194.html
标签:python,列表去重
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
教你如何在WordPress发布文章时自定义文章作者名称
2023-11-12 07:47:11
![](https://img.aspxhome.com/file/2023/9/132249_0s.jpg)
Go语言实现简单留言板的方法
2024-02-12 05:51:42
C#操作本地文件及保存文件到数据库的基本方法总结
2024-01-17 10:27:55
selenium 多窗口切换的实现(windows)
2021-08-17 03:58:54
Python中requests、aiohttp、httpx性能比拼
2023-10-17 05:27:26
MySql用DATE_FORMAT截取DateTime字段的日期值
2024-01-14 02:48:22
Python标准库之随机数 (math包、random包)介绍
2021-09-26 11:57:08
python 对dataframe下面的值进行大规模赋值方法
2022-01-08 07:04:19
Go 语言结构体链表的基本操作
2024-02-07 18:51:11
![](https://img.aspxhome.com/file/2023/4/101044_0s.png)
mysql mycat 中间件安装与使用
2024-01-21 11:35:48
python如何将图片转换素描画
2022-05-26 23:17:49
![](https://img.aspxhome.com/file/2023/2/91842_0s.png)
MySQL DQL语句的具体使用
2024-01-21 08:17:03
Python脚本实现网卡流量监控
2022-11-27 11:36:51
switchery按钮的使用方法
2024-04-29 13:40:44
![](https://img.aspxhome.com/file/2023/3/132593_0s.png)
Django Celery异步任务队列的实现
2023-09-28 19:24:53
MySQL字符集 GBK、GB2312、UTF8区别 解决MYSQL中文乱码问题
2024-01-14 03:16:56
深入C++ string.find()函数的用法总结
2024-01-13 05:21:48
微信小程序 swiper 组件遇到的问题及解决方法
2024-04-18 09:40:47
将MySQL数据库移植为PostgreSQL
2024-01-21 22:20:09
golang正则之命名分组方式
2024-05-22 10:17:10