python按不同条件对元组进行排序 [英] python sort tuple by different criteria

查看:89
本文介绍了python按不同条件对元组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表a = [(1,'a'), (1,'b'), (2,'c')],我想获取此列表:[(2,'c'), (1,'a'), (1,'b')]

I have a list a = [(1,'a'), (1,'b'), (2,'c')], and I want to get this list: [(2,'c'), (1,'a'), (1,'b')]

如果我这样做:

sorted(a, reverse=True)

我只能得到:

[(2,'c'), (1,'b'), (1,'a')]

如何获取我想要的列表?

How can I get the list I want?

推荐答案

您可以通过将lambda函数与sorted一起使用来实现此目的:

You may achieve this by using lambda function with sorted:

>>> sorted(a, key=lambda x: (-x[0], x[1]))
[(2, 'c'), (1, 'a'), (1, 'b')]

这将对列表按索引0处的值的降序进行排序,然后按索引1处的值的升序进行排序

This will sort the list in descending order of the value at index 0, and then ascending order of value at index 1

这篇关于python按不同条件对元组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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