Python unique list using set(使用集合的 Python 唯一列表)
问题描述
可能重复:
如何从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]
这篇关于使用集合的 Python 唯一列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用集合的 Python 唯一列表


基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01