如何从 Python 列表中删除重复项并保持顺序? [英] How to remove duplicates from Python list and keep order?

查看:30
本文介绍了如何从 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
  • 这篇关于如何从 Python 列表中删除重复项并保持顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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