gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:44:50 26 4
gpt4 key购买 nike

<分区>

我遇到了很多任务,在这些任务中我需要过滤 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))]

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com