Python中移除List重复项的五种方法
作者:卓晴 发布时间:2021-12-11 20:15:38
本文列些处几种去除在Python 列表中(list)可能存在的重复项,这在很多应用程序中都会遇到的需求,作为程序员最好了解其中的几种方法 以备在用到时能够写出有效的程序。
方法1:朴素方法
这种方式是在遍历整个list的基础上,将第一个出现的元素添加在新的列表中。
示例代码:
# Python 3 code to demonstrate
# removing duplicated from list
# using naive methods
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print ("The original list is : " + str(test_list))
# using naive method
# to remove duplicated
# from list
res = []
for i in test_list:
if i not in res:
res.append(i)
# printing list after removal
print ("The list after removing duplicates : " + str(res))
→ 输出结果:
The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 3, 5, 6]
方法2:列表解析式
这种方式实际上是第一种方法的简化版,它利用列表解析式,使用一行代码就可以替代上面的循环方式。
示例代码:
# Python 3 code to demonstrate
# removing duplicated from list
# using list comprehension
# initializing list
test_list = [1, 3, 5, 6, 3, 5, 6, 1]
print ("The original list is : " + str(test_list))
# using list comprehension
# to remove duplicated
# from list
res = []
[res.append(x) for x in test_list if x not in res]
# printing list after removal
print ("The list after removing duplicates : " + str(res))
→ 输出结果:
The original list is : [1, 3, 5, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 3, 5, 6]
方法3:使用set()
这种方式是最流行的方法来去除列表中的重复元素。但该方法的最大的一个缺点就是使用过后列表中元素的顺序不再继续保持与原来一致了。
示例代码:
# Python 3 code to demonstrate
# removing duplicated from list
# using set()
# initializing list
test_list = [1, 5, 3, 6, 3, 5, 6, 1]
print ("The original list is : " + str(test_list))
# using set()
# to remove duplicated
# from list
test_list = list(set(test_list))
# printing list after removal
# distorted ordering
print ("The list after removing duplicates : " + str(test_list))
→ 输出结果:
The original list is : [1, 5, 3, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 3, 5, 6]
方法4:利用列表解析式 + enumerate()
该方法是在列表解析式的基础上利用枚举来去除重复元素。通过检查元素是否已经在列表中存在从而将其略过。这种方法可以保持列表中的元素顺序不会改变。
示例代码:
# Python 3 code to demonstrate
# removing duplicated from list
# using list comprehension + enumerate()
# initializing list
test_list = [1, 5, 3, 6, 3, 5, 6, 1]
print ("The original list is : " + str(test_list))
# using list comprehension + enumerate()
# to remove duplicated
# from list
res = [i for n, i in enumerate(test_list) if i not in test_list[:n]]
# printing list after removal
print ("The list after removing duplicates : " + str(res))
→ 输出结果:
The original list is : [1, 5, 3, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 5, 3, 6]
方法5:利用collections.OrderedDict.fromkeys()
这是完成特殊任务中最快的方法。它先是将列表中的重复项移除并返回一个字典,最后转换成列表。这种方法对于字符串也可以进行处理。
示例代码:
# Python 3 code to demonstrate
# removing duplicated from list
# using collections.OrderedDict.fromkeys()
from collections import OrderedDict
# initializing list
test_list = [1, 5, 3, 6, 3, 5, 6, 1]
print ("The original list is : " + str(test_list))
# using collections.OrderedDict.fromkeys()
# to remove duplicated
# from list
res = list(OrderedDict.fromkeys(test_list))
# printing list after removal
print ("The list after removing duplicates : " + str(res))
→ 输出结果:
The original list is : [1, 5, 3, 6, 3, 5, 6, 1]
The list after removing duplicates : [1, 5, 3, 6]
方法6:处理嵌套列表中的重复元素
对于多维列表(列表嵌套)中的重复元素去除。这里假设列表中元素(也是列表)它们具有相同的元素(但不一定顺序相同)都被当做重复元素。那么下面使用 set() + sorted() 方法来完成任务。
示例代码:
# Python3 code to demonstrate
# removing duplicate sublist
# using set() + sorted()
# initializing list
test_list = [[1, 0, -1], [-1, 0, 1], [-1, 0, 1],
[1, 2, 3], [3, 4, 1]]
# printing original list
print("The original list : " + str(test_list))
# using set() + sorted()
# removing duplicate sublist
res = list(set(tuple(sorted(sub)) for sub in test_list))
# print result
print("The list after duplicate removal : " + str(res))
→ 输出结果:
The original list : [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]]
The list after duplicate removal : [(-1, 0, 1), (1, 3, 4), (1, 2, 3)]
也可以利用 set() + map() + sorted()
示例代码:
# Python3 code to demonstrate
# removing duplicate sublist
# using set() + map() + sorted()
# initializing list
test_list = [[1, 0, -1], [-1, 0, 1], [-1, 0, 1],
[1, 2, 3], [3, 4, 1]]
# printing original list
print("The original list : " + str(test_list))
# using set() + map() + sorted()
# removing duplicate sublist
res = list(set(map(lambda i: tuple(sorted(i)), test_list)))
# print result
print("The list after duplicate removal : " + str(res))
→ 输出结果:
The original list : [[1, 0, -1], [-1, 0, 1], [-1, 0, 1], [1, 2, 3], [3, 4, 1]]
The list after duplicate removal : [(-1, 0, 1), (1, 3, 4), (1, 2, 3)]
来源:https://blog.csdn.net/zhuoqingjoking97298/article/details/116946704


猜你喜欢
- 当元素设置浮动(float)后会被移出文档流,相信大家都会经常遇到这样的问题。这问题的解决办法有N种之多,因为每种浏览器对CSS的解析各异,
- 刚看到一个朋友写的用javascript连接excel数据库的程序,想把它改成access数据库的,就找到了这两篇文章 ----------
- 我就废话不多说了,大家还是直接看代码吧~# 两个依赖包: sasl&thriftThe easier way I find to i
- 1. FILE APIhtml5提供了FIle和FileReader两个方法,可以读取文件信息并读取文件。2. example<htm
- 前言最近在学习python-igraph,发现其实学习一种全新的语言看官方的文档是真的很有帮助,这次我的大部分python代码的完成都是靠着
- 摘要一直比较想知道图片经过卷积之后中间层的结果,于是使用pytorch写了一个脚本查看,先看效果这是原图,随便从网上下载的一张大概224*2
- 我们日常生活中经常会使用浏览器访问Web站点这个过程中到底发生了什么吗?为什么我们在浏览器地址栏上面输入要访问的URL后就可以访问到Web页
- 1.urlopen()方法urllib.urlopen(url[, data[, proxies]]) :创建一个表示远程url的类文件对象
- 索引和切片是NumPy中最重要最常用的操作。熟练使用NumPy切片操作是数据处理和机器学习的前提,所以一定要掌握好。文档:https://d
- 本文代码将一些简单常用的SQL语句,拆分、封装成链式函数与终结函数,链式操作没有先后之分,实现傻瓜式mysql数据库操作。 同时学习下静态成
- 1、什么是全局变量?在Python中,全局变量指的是可以作用于函数内部和外部的变量。在这里有两种情况:在函数的外部定义和内部定义添加glob
- 最近项目里要做一个画板,需要对键盘事件进行监听,来进行诸如撤回、重做、移动、缩放等操作,因此顺手实现了一个键盘事件监听控件,期间略有收获,整
- 本文为大家分享了华为校园招聘上机笔试题,供大家参考,具体内容如下[编程题] 扑克牌大小时间限制:10秒空间限制:131072K扑克牌游戏大家
- 编写tasks.pyfrom celery import Celeryfrom tornado.httpclient import HTTP
- 线程和进程1、线程共享创建它的进程的地址空间,进程有自己的地址空间2、线程可以访问进程所有的数据,线程可以相互访问3、线程之间的数据是独立的
- <html> <head> <meta charset="utf-8"/> <
- 函数的作用域python中的作用域分4种情况:L:local,局部作用域,即函数中定义的变量;E:enclosing,嵌套的父级函数的局部作
- asyncio介绍熟悉c#的同学可能知道,在c#中可以很方便的使用 async 和 await 来实现异步编程,那么在p
- 0x01 生成shellcode首先通过下列命令生成一个shellcode,使用msfvenom -p选项来指定paylaod,这里选用wi
- 前言关于mockjs,官网描述的是1.前后端分离2.不需要修改既有代码,就可以拦截 Ajax 请求,返回模拟的响应数据。3.数据类型丰富4.