使用set的Python唯一列表 [英] Python unique list using set

查看:83
本文介绍了使用set的Python唯一列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何从中删除重复项保留顺序的同时用Python创建一个列表?

Possible Duplicate:
How do you remove duplicates from a list in Python whilst preserving order?

我想做的是编写一个方法,该方法将列表作为参数,并使用一组方法返回列表的副本,其中每个元素仅出现一次,并且使新列表中的元素出现在列表中.它们在原始列表中首次出现的顺序.我必须为此使用一个集合,但是,我无法使它以正确的顺序输出,同时又有快速的结果. 如果我放这样的东西:

What I am trying to do is write a method that takes a list as an argument and uses a set to return a copy of the list where each element only occurs once, as well as having the elements in the new list occur in order of their first occurrence in the original list. I HAVE to use a set for this, however, I can't make it so that the output is in the right order while having a quick result. If I put something like this:

def unique(a):

return list(set(a))

并传递了包含数百万个元素的列表,它会很快给我一个结果,但不会被排序. 所以我现在是这样的:

and passed a list with millions of elements, it would give me a result quickly, but it wouldn't be ordered. So what I have right now is this:

def unique(a):
b = set(a)
c = {}
d = []
for i in b:
    c[a.index(i)] = i
for i in c:
    d.append(c[i])
return d

这给了我想要的结果,但是速度不够快.如果我通过一个包含一百万个元素的列表,我可能要等待半个小时,而那里的一个班轮花费的时间不到一秒钟.我该如何解决这个问题?

This gives me the result I want, but not fast enough. If I pass a list with a million elements, I could be waiting for half an hour, whereas the one liner up there takes less than a second. How could I solve this problem?

推荐答案

>>> from collections import OrderedDict
>>> items = [1, 2, 3, 'a', 2, 4, 'a']
>>> OrderedDict.fromkeys(items).keys()
[1, 2, 3, 'a', 4]

这篇关于使用set的Python唯一列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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