在 Python 中,从列表中删除重复项以便所有元素都是唯一的*同时保持顺序*的最快算法是什么? [英] In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique *while preserving order*?

查看:9
本文介绍了在 Python 中,从列表中删除重复项以便所有元素都是唯一的*同时保持顺序*的最快算法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

<预><代码>>>>x = [1, 1, 2, 'a', 'a', 3]>>>独特的(x)[1, 2, 'a', 3]

假设列表元素是可散列的.

说明:结果应保留列表中的第一个重复项.例如, [1, 2, 3, 2, 3, 1] 变为 [1, 2, 3].

解决方案

def unique(items):找到 = 设置([])保持 = []对于项目中的项目:如果未找到项目:找到.添加(项目)keep.append(item)返回保持打印唯一的([1, 1, 2, 'a', 'a', 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 中,从列表中删除重复项以便所有元素都是唯一的*同时保持顺序*的最快算法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆