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

你可能感兴趣的文章
NLP项目:维基百科文章爬虫和分类【02】 - 语料库转换管道
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
nmap 使用方法详细介绍
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
nmap指纹识别要点以及又快又准之方法
查看>>
Nmap渗透测试指南之指纹识别与探测、伺机而动
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
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 compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>