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 脚本监听来自另一个脚本的输入 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 筛选NumPy数组 2022-01-01