Python中有几种方法实现列表去重,代码是什么
Admin 2022-08-01 群英技术资讯 985 次浏览
这篇文章将为大家详细讲解有关“Python中有几种方法实现列表去重,代码是什么”的知识,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。请定义函数,将列表[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))
运行结果:

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇博文的目的是从图片中提取一定的矩形区域作为新的图片 简单来说:我的全家福丢了,所以我想从以前的房间照片里,提取出其中的全家福并重新打印一张(忽视画质问题)现在我就是这么个目的,需要的朋友可以参考下
这篇文章主要介绍了TensorFlow2如何实现前向传播,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
python int是什么意思?python中的int()函数用于将一个字符串或数字转换为整型。
python模块重载的方法有哪些?一些新手对于python模块重载的方法不是很了解,对此下面给大家分享几个python模块重载的方法,供大家参考,希望能对大家学习Python有帮助。
这篇文章主要介绍了pycharm中keras导入报错无法自动补全cannot find reference分析,文章围绕主题展开分析,需要的小伙伴可以参考一下
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008