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

你可能感兴趣的文章
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad++最详情汇总
查看>>
notepad++正则表达式替换字符串详解
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notes on Paul Irish's "Things I learned from the jQuery source" casts
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
NotImplementedError: Could not run torchvision::nms
查看>>
nova基于ubs机制扩展scheduler-filter
查看>>
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 ‘html-webpack-plugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>