您现在的位置是:网站首页> 编程资料编程资料
Python列表去重的几种方法整理_python_
2023-05-26
351人已围观
简介 Python列表去重的几种方法整理_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
方法四:巧用字典
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列表去重的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。
您可能感兴趣的文章:
相关内容
- PyCharm设置中文(汉化与解除汉化)的方法_python_
- Python简繁体转换的简单实现步骤_python_
- Mac下python包管理工具pip的安装_python_
- Caffe数据可视化环境python接口配置教程示例_python_
- Python命令行库click的具体使用_python_
- Mac下使用HomeBrew安装python3_python_
- Python识别二维码的两种方法详解_python_
- Python实现轻松识别数百个快递单号_python_
- 导入pytorch时libmkl_intel_lp64.so找不到问题解决_python_
- python数字图像处理之边缘轮廓检测_python_
