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
投稿

猜你喜欢

  • python爬取免费代理并验证代理是否可用

    2021-12-24 20:02:48
  • js实现贪吃蛇游戏含注释

    2024-04-19 10:05:44
  • php下防止单引号,双引号在接受页面转义的设置方法

    2023-11-15 02:37:01
  • JavaScript Length 字符长度函数

    2008-12-12 12:29:00
  • MySQL该如何判断不为空详析

    2024-01-22 03:10:31
  • Python和Sublime整合过程图示

    2023-04-11 15:23:33
  • python实现单机五子棋

    2021-04-26 05:34:35
  • Python实现获取视频时长功能

    2021-11-25 03:33:57
  • python httpx的具体使用

    2021-05-31 21:42:28
  • MySQL定时备份之使用Linux下的crontab定时备份实例

    2024-01-18 01:43:52
  • Python网络爬虫与信息提取(实例讲解)

    2022-10-27 20:53:04
  • python下MySQLdb用法实例分析

    2024-01-18 11:50:27
  • Python切片操作深入详解

    2021-07-06 08:39:26
  • 利用Python爬虫给孩子起个好名字

    2022-04-25 23:40:29
  • 详解git reset 加不加 --hard的区别

    2022-04-03 06:45:13
  • delete from online where datediff

    2009-06-07 18:46:00
  • Python多线程中阻塞(join)与锁(Lock)使用误区解析

    2022-03-22 08:00:31
  • 网页设计三剑客

    2010-08-31 17:05:00
  • Pytest单元测试框架生成HTML测试报告及优化的步骤

    2021-07-10 16:49:13
  • Python实现Opencv cv2.Canny()边缘检测

    2022-12-01 13:26:37
  • asp之家 网络编程 m.aspxhome.com