在Python中删除重复项的最快方法 [英] Fastest Way to remove Duplicates in Python

查看:102
本文介绍了在Python中删除重复项的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正尝试使用以下代码从列表中删除重复项:

I was trying to remove duplicates from a list using the following code:

a = [1,2,3,4,2,6,1,1,5,2]
res = []
[res.append(i) for i in a if i not in res]

但是我希望不将想要的列表定义为空列表(例如,省略行res = [])来执行此操作,例如:

But I would like to do this without defining the list I want as an empty list (ie, omit the line res = []) like:

a = [1,2,3,4,2,6,1,1,5,2]
#Either:
res = [i for i in a if i not in res]
#Or:
[i for i in a if i not in 'this list'] # this list is not a string. I meant it as the list being comprehensed

我想避免库导入和set()

推荐答案

对于Python3.6 +,您可以使用dict.fromkeys():

For Python3.6+, you can use dict.fromkeys():

>>> a = [1, 2, 3, 4, 2, 6, 1, 1, 5, 2]
>>> list(dict.fromkeys(a))
[1, 2, 3, 4, 6, 5]

文档:

使用可迭代键并将值设置为value来创建新字典.

Create a new dictionary with keys from iterable and values set to value.

如果您使用的是较低版本的Python,则需要使用 collections.OrderedDict 保持顺序:

If you are using a lower Python version, you will need to use collections.OrderedDict to maintain order:

>>> from collections import OrderedDict
>>> a = [1, 2, 3, 4, 2, 6, 1, 1, 5, 2]
>>> list(OrderedDict.fromkeys(a))
[1, 2, 3, 4, 6, 5]

这篇关于在Python中删除重复项的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆