在 Python 列表上进行排序加 uniq 的最简洁方法是什么? [英] What is the cleanest way to do a sort plus uniq on a Python list?

查看:27
本文介绍了在 Python 列表上进行排序加 uniq 的最简洁方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个包含 ['foo', 'foo', 'bar'] 的 Python 列表 my_list.

Consider a Python list my_list containing ['foo', 'foo', 'bar'].

统一和对列表进行排序的最 Pythonic 方式是什么?
(想想 cat my_list | sort | uniq)

What is the most Pythonic way to uniquify and sort a list ?
(think cat my_list | sort | uniq)

这就是我目前的做法,虽然它有效,但我相信有更好的方法可以做到.

This is how I currently do it and while it works I'm sure there are better ways to do it.

my_list = []
...
my_list.append("foo")
my_list.append("foo")
my_list.append("bar")
...
my_list = set(my_list)
my_list = list(my_list)
my_list.sort()

推荐答案

my_list = sorted(set(my_list))

这篇关于在 Python 列表上进行排序加 uniq 的最简洁方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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