Python实现去除列表中重复元素的方法


本文摘自php中文网,作者不言,侵删。

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

#!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 "脚本之家测试结果:"

  print func1(one_list)

  print func2(one_list)

  print func3(one_list)

  print func4(one_list)

结果如下:

脚本之家测试结果:
[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]

运行结果截图:

相关推荐:

python 删除非空文件夹的实例

python实现图书馆研习室自动预约功能

Python Requests模拟登录实现图书馆座位自动预约


以上就是Python实现去除列表中重复元素的方法的详细内容,更多文章请关注木庄网络博客!!

相关阅读 >>

Python如何调用r

Python中集合是什么?简单的集合操作

怎么在Python安装bs4

Python函数参数默认值的用法及注意要点

Python的关键字有哪些

Python中flask_migrate,flask_script的使用介绍(附代码)

介绍Python应用学习之qrcode生成二维码

Python用什么软件好?Python开发工具推荐

认识Python的json.dumps()和json.loads()

Python爬虫怎么设置请求头

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...