Python去除列表中重复元素的方法
作者:ijoy_360 时间:2021-06-23 20:44:27
本文实例讲述了Python去除列表中重复元素的方法。分享给大家供大家参考。具体如下:
比较容易记忆的是用内置的set
l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
print l2
还有一种据说速度更快的,没测试过两者的速度差别
l1 = ['b','c','d','b','c','a','a']
l2 = {}.fromkeys(l1).keys()
print l2
这两种都有个缺点,祛除重复元素后排序变了:
['a', 'c', 'b', 'd']
如果想要保持他们原来的排序:
用list类的sort方法
l1 = ['b','c','d','b','c','a','a']
l2 = list(set(l1))
l2.sort(key=l1.index)
print l2
也可以这样写
l1 = ['b','c','d','b','c','a','a']
l2 = sorted(set(l1),key=l1.index)
print l2
也可以用遍历
l1 = ['b','c','d','b','c','a','a']
l2 = []
for i in l1:
if not i in l2:
l2.append(i)
print l2
上面的代码也可以这样写
l1 = ['b','c','d','b','c','a','a']
l2 = []
[l2.append(i) for i in l1 if not i in l2]
print l2
这样就可以保证排序不变了:
['b', 'c', 'd', 'a']
希望本文所述对大家的Python程序设计有所帮助。
标签:Python,列表,重复,元素
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
JavaScript table的排序类
2008-10-06 12:56:00
JScript下Array对象的性能问题
2009-02-15 12:28:00
Python+OpenCV之图像轮廓详解
2023-08-10 18:59:42
![](https://img.aspxhome.com/file/2023/1/62001_0s.png)
Anaconda+spyder+pycharm的pytorch配置详解(GPU)
2023-07-20 01:31:20
![](https://img.aspxhome.com/file/2023/0/64320_0s.png)
[译]开发人员经常犯的8个设计错误
2008-02-01 12:28:00
![](https://img.aspxhome.com/file/uploadpic/20082/1/200821125136512.gif)
Oracle轻松取得建表和索引的DDL语句
2009-02-26 10:26:00
Python使用py2exe打包程序介绍
2023-11-12 21:29:55
理解绝对定位和相对定位布局
2009-03-19 13:53:00
![](https://img.aspxhome.com/file/UploadPic/20093/19/328_001-17s.jpg)
PHP之深入学习Yii2缓存Cache组件详细讲解
2023-06-29 17:37:20
![](https://img.aspxhome.com/file/2023/1/55561_0s.jpg)
模拟实现 Range 的 insertNode() 方法
2010-11-30 21:39:00
ActionScript3.0是革命性的
2008-05-01 12:36:00
![](https://img.aspxhome.com/file/UploadPic/20085/1/200851124819630s.jpg)
互联网产品交互事件分析
2009-10-06 15:23:00
asp加载access数据库并生成XML文件范例
2008-07-22 12:41:00
asp如何正确理解MIME类型?
2010-06-28 18:21:00
asp如何制作一个弹出式的调查窗口?
2010-06-29 21:24:00
关于淘宝页面编码的疑惑
2009-12-04 12:54:00
![](https://img.aspxhome.com/file/UploadPic/200912/4/p_large_lfyx_571d000732d42d0c-25s.jpg)
Python3控制路由器——使用requests重启极路由.py
2023-05-20 08:07:54
js控制多图左右滚动切换效果代码分享
2023-08-28 00:14:32
![](https://img.aspxhome.com/file/2023/0/56190_0s.jpg)
考虑SQL Server安全时所应注意的几个方面
2009-01-04 13:57:00
数据库基础:MySQL 添加用户的两种方法
2009-05-07 14:26:00