python - 将 Python 列表转换为有序的唯一值

标签 python python-2.7 list ordereddictionary

<分区>

我遇到了很多任务,在这些任务中我需要过滤 python (2.7) 列表以仅保留有序的唯一值。我常用的方法是使用集合中的 odereddict:

from collections import OrderedDict

ls = [1,2,3,4,1,23,4,12,3,41]

ls = OrderedDict(zip(ls,['']*len(ls))).keys()

print ls

输出是:

[1, 2, 3, 4, 23, 12, 41]

有没有其他最先进的方法可以在 Python 中做到这一点?

  • 注意 - 输入和输出应作为 list

编辑 - 可以在此处找到方法的比较: https://www.peterbe.com/plog/uniqifiers-benchmark

同时最好的解决方案是:

def get_unique(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]

最佳答案

你可以使用 set像这样:

newls = []
seen = set()

for elem in ls:
    if not elem in seen:
        newls.append(elem)
        seen.add(elem)

关于python - 将 Python 列表转换为有序的唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44628186/

相关文章:

python - 使用 asyncio/aiohttp 未完成响应负载

python - 8 位校验和差一

python - 从expect脚本调用python脚本时出错

python - 可执行构建闪烁并终止

python - 使用 python 编辑 outlook 分发列表

r - 寻找替换列表中字符向量元素的方法

list - Prolog - 在列表中创建累积重复项?

python - 无法对 Pandas DataFrame 进行排序

python - 如何处理用 Pandas 导入的数据?

python - 为什么 python 中的 'for' 循环会更改未引用的列表?