• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python实现去除列表中重复元素的方法小结【4种方法】

python 搞代码 4年前 (2022-01-07) 62次浏览 已收录 0个评论

这篇文章主要介绍了Python实现去除列表中重复元素的方法,结合实例形式总结分析了Python列表去重的4种实现方法,涉及Python针对列表的遍历、判断、排序等相关操作技巧,需要的朋友可以参考下

本文实例讲述了Python实现去除列表中重复元素的方法。分享给大家供大家参考,具体如下:

这里一共使用了四种方法来去除列表中的重复元素,下面是具体实现:

 #!usr/bin/env python #encoding:utf-8 ''' __Author__:沂水寒城 功能:去除列表中的重复元素 ''' def func1(one_list): ''''' 使用集合,个人最常用 ''' return list(set(one_list)) def func2(one_list): ''''' 使用字典的方式 ''' return {}.fromkeys(one_list).keys() def func3(one_list): ''''' 使用列表推导的方式 ''' temp_list=[] for one in one_list: if one not in temp_list: temp_list.append(one) return temp_list def func4(one_list): ''''' 使用排序的方法 ''' result_list=[] temp_list=sorted(one_list) i=0 while i<len(temp_list): if temp_list[i] not in result_list: result_list.append(temp_list[i]) else: i+=1 return result_list if __name__ == '__main__': one_list=[56,7,4,23,56,9,0,56,12,3,56,34,45,5,6,56] print "<a href="http://www.gaodaima.com">gaodaima搞代码网</a>测试结果:" print func1(one_list) print func2(one_list) print func3(one_list) print func4(one_list) 

结果如下:

gaodaima搞代码网测试结果:
[0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]
[0, 34, 3, 4, 5, 6, 7, 9, 12, 45, 23, 56]
[56, 7, 4, 23, 9, 0, 12, 3, 34, 45, 5, 6]
[0, 3, 4, 5, 6, 7, 9, 12, 23, 34, 45, 56]

运行结果截图:

PS:本站还有两款比较简单实用的在线文本去重复工具,推荐给大家使用:

在线去除重复项工具:
http://tools.gaodaima.com/code/quchong

在线文本去重复工具:
http://tools.gaodaima.com/aideddesign/txt_quchong

更多关于Python相关内容可查看本站专题:《Python字典操作技巧汇总》、《Python字符串操作技巧汇总》、《Python常用遍历技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》及《Python入门与进阶经典教程》

希望本文所述对来源gao@dai!ma.com搞$代^码网大家Python程序设计有所帮助。

以上就是Python实现去除列表中重复元素的方法小结【4种方法】的详细内容,更多请关注gaodaima搞代码网其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python实现去除列表中重复元素的方法小结【4种方法】

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址