Python代码实现删除一个list里面重复元素的方法
作者:melody_1314 时间:2022-06-02 15:31:02
网上学习了的两个新方法,代码非常之简洁。看来,不是只要实现了基本功能就能交差滴,想要真的学好python还有很长的一段路呀
方法一:是利用map的fromkeys来自动过滤重复值,map是基于hash的,大数组的时候应该会比排序快点吧
方法二:是用set(),set是定义集合的,无序,非重复
方法三:是排序后,倒着扫描,遇到已有的元素删之
#!/usr/bin/python
#coding=utf-8
'''
Created on 2012-2-22
Q: 给定一个列表,去掉其重复的元素,并输出
'''
def distFunc1():
a=[1,2,4,2,4,5,6,5,7,8,9,0]
b={}
b=b.fromkeys(a)
print b
#print b.keys()
a=list(b.keys())
print a
def distFunc2():
a=[1,2,4,2,4,5,7,10,5,5,7,8,9,0,3]
a=list(set(a)) # set是非重复的,无序集合。可以用list来的排队对set进行排序,list()转换为列表,a.sort来排序
print a
def distFunc3():
#可以先把list重新排序,然后从list的最后开始扫描,代码如下:
List=[1,2,4,2,4,5,7,10,5,5,7,8,9,0,3]
if List:
List.sort()
#print List
last = List[-1]
#print last
for i in range(len(List)-2, -1, -1):
if last==List[i]:
del List[i]
else: last=List[i]
if __name__ == '__main__':
distFunc1()
distFunc2()
distFunc3()
请写出一段 Python 代码实现删除一个 list 里面的重复元素
可以先把 list 重新排序,然后从 list 的最后开始扫描,代码如下:
In [8]: List = [1, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7]
In [9]: if List:
...: List.sort()
...: last = List[-1]
...: for i in range(len(List)-2, -1, -1):
...: if last==List[i]:
...: del List[i]
...: else:
...: last=List[i]
...: print(List)
[1, 2, 3, 4, 5, 6, 7]
来源:https://blog.csdn.net/melody_1314/article/details/7298448
标签:python,list,删除重复元素
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现udp传输图片功能
2022-09-24 16:35:01
![](https://img.aspxhome.com/file/2023/2/67752_0s.jpg)
浅谈Pandas Series 和 Numpy array中的相同点
2022-06-11 15:20:17
Python从使用线程到使用async/await的深入讲解
2021-07-26 10:56:11
Tensorflow2.1 MNIST图像分类实现思路分析
2023-04-17 03:35:32
Python并发编程实例教程之线程的玩法
2022-02-02 08:17:41
python用字符组成图像代码实例
2023-09-15 02:12:04
![](https://img.aspxhome.com/file/2023/7/62597_0s.jpg)
浅谈Python线程的同步互斥与死锁
2022-06-26 17:38:37
![](https://img.aspxhome.com/file/2023/9/79799_0s.png)
带农历及节日的js日历源码
2010-08-01 17:38:00
![](https://img.aspxhome.com/file/UploadPic/20108/1/201081174033330s.jpg)
解决jupyter (python3) 读取文件遇到的问题
2021-02-05 10:00:25
Python OpenCV实现图像傅里叶变换
2022-06-19 04:43:55
![](https://img.aspxhome.com/file/2023/4/92314_0s.png)
解决在Python编辑器pycharm中程序run正常debug错误的问题
2023-09-09 09:58:39
![](https://img.aspxhome.com/file/2023/6/128206_0s.jpg)
JavaScript入门学习书籍的阶段选择
2008-01-11 19:39:00
浅谈PHP中的Trait使用方法
2023-11-08 09:25:33
![](https://img.aspxhome.com/file/2023/8/55738_0s.png)
Python中获取网页状态码的两个方法
2023-08-27 22:47:21
Python稀疏矩阵及参数保存代码实现
2021-05-10 08:18:34
![](https://img.aspxhome.com/file/2023/2/123462_0s.png)
基于php权限分配的实现代码
2023-11-14 11:10:49
![](https://img.aspxhome.com/file/2023/3/94503_0s.png)
python使用BeautifulSoup分页网页中超链接的方法
2023-11-21 07:24:49
Python OpenCV阈值处理详解
2023-10-07 19:38:47
![](https://img.aspxhome.com/file/2023/2/80592_0s.png)
深入浅析Python2.x和3.x版本的主要区别
2023-06-21 04:12:52
python如何通过psutil获取服务器cpu、内存、磁盘使用率
2022-11-07 01:01:29