python:如何对两个不同的键上的复杂列表进行排序 [英] python: how to sort a complex list on two different keys

查看:92
本文介绍了python:如何对两个不同的键上的复杂列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过以下方式构建了一个怪异列表:

I have a weird list built in the following way:

[[name_d, 5], [name_e, 10], [name_a, 5]] 

,我想先按数字(desc)对其进行排序,然后,如果数字相同,则按名称(asc)对其进行排序.所以我想得到的结果是:

and I want to sort it first by the number (desc) and then, if the number is the same, by the name (asc). So the result I would like to have is:

[[name_e, 10], [name_a, 5], [name_d, 5]]

我试图考虑一个可以在sort方法中使用的lambda函数,但是我不确定我能做到这一点.

I tried to think to a lambda function that I can use in the sort method, but I'm not sure I can do it.

推荐答案

python中的排序函数允许将函数作为排序键:

Sort functions in python allow to pass a function as sort key:

l = [[name_d, 5], [name_e, 10], [name_a, 5]]
# copy
l_sorted = sorted(l, key=lambda x: (x[1] * -1, x[0]))
# in place
l.sort(key=lambda x: (x[1] * -1, x[0]))


1.排序顺序
2.演示复制和就位排序

Edits:
1. Sort order
2. Demonstrate copy and in place sorting

这篇关于python:如何对两个不同的键上的复杂列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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