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

你可能感兴趣的文章
NotImplementedError: Could not run torchvision::nms
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>
npm install 报错 Failed to connect to github.com port 443 的解决方法
查看>>