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

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

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