博客
关于我
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/

你可能感兴趣的文章
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>
npm,yarn,cnpm 的区别
查看>>
NPOI
查看>>
NPOI之Excel——合并单元格、设置样式、输入公式
查看>>
NPOI初级教程
查看>>