使用 set 的 Python 唯一列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12878833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python unique list using set
提问by user1744238
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?
这给了我想要的结果,但不够快。如果我传递一个包含一百万个元素的列表,我可能要等半个小时,而在那里排队的时间不到一秒钟。我怎么能解决这个问题?
采纳答案by jamylak
>>> from collections import OrderedDict
>>> items = [1, 2, 3, 'a', 2, 4, 'a']
>>> OrderedDict.fromkeys(items).keys()
[1, 2, 3, 'a', 4]

