如何从 Python 列表中删除重复项并保持顺序? [英] How to remove duplicates from Python list and keep order?
本文介绍了如何从 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))
查看全文