对列表进行升序然后降序排序 [英] Sort list of lists ascending and then descending

查看:46
本文介绍了对列表进行升序然后降序排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个包含看起来像这样的列表的列表

If I have a list that contains a list that looks like this

['a',1] ['a',2] ['a',3] ['b',1] ['b',2] ['b',3]

如何对它们进行排序,以便元素 0 降序排序,元素 1 升序排序,以便结果看起来像

How can I sort them so that element 0 is sorted descending and element 1 sorted ascending so the result would look like

['b',1] ['b',2] ['b',3] ['a',1] ['a',2] ['a',3]

使用 itemgetter 我可以在元素 0 上反向传递,但我然后诉诸于元素,当然它破坏了以前的排序.我不能做组合键,因为它需要先降序然后升序.

Using itemgetter I can pass in reverse on element 0 but I then resort against element to of course it ruins the previous sort. I can't do a combined key since it needs to first sort descending and then ascending.

推荐答案

L = [['a',1], ['a',2], ['a',3], ['b',1], ['b',2], ['b',3]]
L.sort(key=lambda k: (k[0], -k[1]), reverse=True)

L 现在包含:

[['b', 1], ['b', 2], ['b', 3], ['a', 1], ['a', 2], ['a', 3]]

这篇关于对列表进行升序然后降序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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