Python列表去重的几种方法整理

作者:小旭2021 时间:2022-06-18 18:05:17 

请定义函数,将列表[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]中的重复元素除去,写出至少3种方法。

方法一:利用集合去重

list_1=[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func1(list_1):
  return list(set(list_1))
print('去重后的列表:',func1(list_1))

方法二:利用for循环

list_2 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func2(list_2):
   #定义一个空列表
   mylist_2=[]
   #i遍历list_2
   for i in list_2:
       #如果i不在mylist_2,则添加到mylist_2
       if i not in mylist_2:
           mylist_2.append(i)
   print(mylist_2)
print(func2(list_2))

方法三:巧用sort()排序

list_3 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func3(list_3):
 result_list=[]
 temp_list=sorted(list_3)
 i=0
 while i<len(temp_list):
     #如果不在result_list则添加进去,否则i+1
   if temp_list[i] not in result_list:
     result_list.append(temp_list[i])
   else:
     i+=1
 return result_list
print(func3(list_3))

方法四:巧用字典

list_4= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func4(list_4):
   #fromkeys() 函数创建一个新字典,获取新字典的键(键值是唯一的)
   result_list = []
   for i in {}.fromkeys(list_4).keys():
       result_list.append(i)
   return result_list
print(func4(list_4))

方法五:利用迭代器

import itertools
list_5= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func5(list_5):
   list_5.sort()
   temp_list= itertools.groupby(list_5)
   result_list=[]
   for i,j in temp_list:
       result_list.append(i)
   return result_list
print(func5(list_5))

运行结果:

Python列表去重的几种方法整理

来源:https://www.cnblogs.com/chenyablog/p/15172766.html

标签:Python,列表,去重
0
投稿

猜你喜欢

  • SQL“多字段模糊匹配关键字查询”

    2008-04-24 14:16:00
  • Python中GIL的使用详解

    2022-02-08 13:36:30
  • Python 获取div标签中的文字实例

    2023-03-27 01:53:53
  • django获取from表单multiple-select的value和id的方法

    2021-11-03 13:13:31
  • Python使用新浪微博API发送微博的例子

    2023-12-22 08:43:45
  • CSS编写过程中常见的10个错误

    2008-05-29 12:49:00
  • zookeeper python接口实例详解

    2023-03-11 01:34:48
  • PyQt5 QTable插入图片并动态更新的实例

    2022-02-11 03:22:43
  • python库sklearn常用操作

    2022-06-24 13:44:33
  • js实现滑动进度条效果

    2023-08-24 03:47:39
  • 文件上传服务器-jupyter 中python解压及压缩方式

    2021-06-03 22:32:21
  • SQL Server 2005日志文件损坏的处理方法

    2008-12-02 14:36:00
  • Python OpenCV实现图像傅里叶变换

    2022-06-19 04:43:55
  • Python操作Excel插入删除行的方法

    2023-08-05 21:13:50
  • Python还能这么玩之用Python做个小游戏的外挂

    2022-12-11 18:27:43
  • 详解在Python中以绝对路径或者相对路径导入文件的方法

    2021-10-09 19:37:24
  • 一实用的table内容排序Javascript类库

    2008-11-02 15:03:00
  • python生成IP段的方法

    2023-07-22 00:00:30
  • python学习之使用Matplotlib画实时的动态折线图的示例代码

    2021-03-03 17:33:31
  • Python函数实现学员管理系统

    2023-06-22 03:32:30
  • asp之家 网络编程 m.aspxhome.com