在Python中,什么是最快的算法,从列表中删除重复项,使所有的元素都是独一无二的,而* preserving秩序*? [英] In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique *while preserving order*?
本文介绍了在Python中,什么是最快的算法,从列表中删除重复项,使所有的元素都是独一无二的,而* preserving秩序*?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
>>> X = [1,1,2,'一','一个',3]
>>>唯一的(X)
并[1,2,'一',3]
假设列表元素是可哈希。
澄清:结果应该保持在列表中的第一个重复。例如,[1,2,3,2,3,1]变为[1,2,3]
解决方案
高清独特的(项目):
发现=集([])
保留= []
在项目的项目:
如果没有找到项:
found.add(项目)
keep.append(项目)
回守
打印唯一的([1,1,2,'一','一个',3])
For example:
>>> x = [1, 1, 2, 'a', 'a', 3]
>>> unique(x)
[1, 2, 'a', 3]
Assume list elements are hashable.
Clarification: The result should keep the first duplicate in the list. For example, [1, 2, 3, 2, 3, 1] becomes [1, 2, 3].
解决方案
def unique(items):
found = set([])
keep = []
for item in items:
if item not in found:
found.add(item)
keep.append(item)
return keep
print unique([1, 1, 2, 'a', 'a', 3])
这篇关于在Python中,什么是最快的算法,从列表中删除重复项,使所有的元素都是独一无二的,而* preserving秩序*?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文