使用集合的 Python 唯一列表

2022-01-17 00:00:00 python list set

问题描述

可能重复:
如何从Python 中的列表同时保持顺序?

我要做的是编写一个方法,该方法将列表作为参数并使用集合返回列表的副本,其中每个元素只出现一次,以及让新列表中的元素出现在它们在原始列表中的首次出现顺序.我必须为此使用一个集合,但是,我无法做到这样才能使输出的顺序正确,同时获得快速的结果.如果我这样写:

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]

相关文章