Python对列表进行排序/先升后降 [英] Python sort list of lists / ascending and then decending

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

问题描述

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

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,但是我随后求助于element当然会破坏先前的排序.我无法执行组合键,因为它需要先降序然后升序.

Using itemgetter I can pass in reverse on element 0 but i 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.

TIA, PK

推荐答案

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]]

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

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