如何从Python列表中删除重复项并保持顺序?

问题描述:

给出一个字符串列表,我想按字母顺序对它进行排序并删除重复项.我知道我可以做到:

Given a list of strings, I want to sort it alphabetically and remove duplicates. I know I can do this:

from sets import Set
[...]
myHash = Set(myList)

但是我不知道如何按字母顺序从哈希中检索列表成员.

but I don't know how to retrieve the list members from the hash in alphabetical order.

我还没有嫁给哈希,因此任何实现此目的的方法都行得通.另外,性能也不是问题,所以我宁愿选择一种在代码中清楚表达的解决方案,而不是一种快速但不透明的解决方案.

I'm not married to the hash, so any way to accomplish this will work. Also, performance is not an issue, so I'd prefer a solution that is expressed in code clearly to a fast but more opaque one.

可以使用内置函数对列表进行排序和重复数据删除:

A list can be sorted and deduplicated using built-in functions:

myList = sorted(set(myList))

  • set 是Python的内置函数> = 2.3
  • sorted 是Python> = 2.4的内置函数
    • set is a built-in function for Python >= 2.3
    • sorted is a built-in function for Python >= 2.4