博客
关于我
Python_总结列表排重方法
阅读量:288 次
发布时间:2019-03-01

本文共 859 字,大约阅读时间需要 2 分钟。

如何去重:五种常见方法的对比分析

去重是一项常见的数据处理任务,以下是五种常见去重方法的实现代码及解释:

方法一:集合的思想

集合具有去重特性,可以通过将列表转换为集合再转换回列表来实现去重操作。

lis = [1, 2, 3, 1, 2, 1, 1]set_lis = list(set(lis))

这种方法简单高效,适合处理简单列表。

方法二:字典+count函数

通过统计每个元素的出现次数,筛选出现次数为一次的元素。

aa = [1, 2, 3, 1, 2, 1, 1]d = {i: aa.count(i) for i in aa}result = [i for i in d if d[i] == 1]

这种方法可读性高,适用于需要保留所有元素的场景。

方法三:内置函数count + remove

通过循环统计并移除重复元素。

aa = [1, 2, 3, 1, 2, 1, 1]for i in aa:    if aa.count(i) > 1:        for j in range(aa.count(i) - 1):            aa.remove(i)

这种方法适用于小型列表,需谨慎处理大数据量。

方法四:普通遍历+切片

检查当前元素在后续元素中是否出现。

aa = [1, 2, 3, 1, 2, 1, 1]new_aa = []for i in range(len(aa)):    if aa[i] not in aa[i+1:]:        new_aa.append(aa[i])

这种方法直观,适合小数据量。

方法五:更加暴力的遍历

逐个检查元素是否已经存在于新列表中。

aa = [1, 2, 3, 1, 2, 1, 1]new_aa = []for i in aa:    if i not in new_aa:        new_aa.append(i)

这种方法简单直观,但效率较低,适合小数据量。

以上方法各有优劣,选择时需根据具体需求进行权衡。

转载地址:http://hlqo.baihongyu.com/

你可能感兴趣的文章
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>