使用不同的顺序按多个键排序 [英] Sort by multiple keys using different orderings
问题描述
可能的重复:
如何编写用于降序值的 Python 排序键函数一个>
在 Python 3 中,使用多个键按字典顺序对对象列表进行排序非常容易.例如:
In Python 3, it's pretty easy to sort a list of objects lexicographically using multiple keys. For example:
items.sort(key = lambda obj: obj.firstname, obj.lastname)
reverse
参数让您指定是要升序还是降序.但是,如果您想按多个键进行排序,但又想第一个键按降序排序,第二个键按升序排序,您会怎么做?
The reverse
argument lets you specify whether you want ascending or descending order. But what do you do in the case where you want to sort by multiple keys, but you want to sort using descending order for the first key, and ascending order for the second?
例如,假设我们有一个具有两个属性的对象,points
和 name
,其中 points
是一个 int
和 name
是一个 str
.我们希望按照 points
以 降序 顺序对这些对象的列表进行排序(以便具有最大点数的对象排在最前面),但是对于具有相同数量的对象points
,我们想按字母顺序(升序)按name
对它们进行排序.
For example, suppose we have an object with two attributes, points
and name
, where points
is an int
and name
is a str
. We want to sort a list of these objects by points
in descending order (so that the object with the greatest number of points comes first), but for objects with an equal number of points
, we want to sort these by name
in alphabetical (ascending) order.
如何实现?
推荐答案
没有内置的方法来处理这个问题.对于一般情况,您必须排序两次:首先按次要排序,然后按主要排序.正如@Mark Ransom 在他的评论中提到的,在许多情况下变量是数字,因此您可以使用负值来翻转排序.
There is no built-in way to handle this. For the general case, you must sort twice: first by the secondary sort, then by the primary sort. As @Mark Ransom mentioned in his comment, in many cases the variables are numeric, and so you can use the negative value to flip the ordering.
如果您知道要排序的变量的类型以及如何使用它,您还可以编写一个键函数,为增加的键返回一个递减的值.有关字符串的示例,请参阅此线程.(基本上,您取字符的 ASCII 数值的负数.)
If you know the type of the variable you're trying to sort on and how to work with it, you could also write a key function that returns a decreasing value for increasing keys. See this thread for an example for strings. (Basically, you take the negative of the ASCII numerical value of the characters.)
在 Python 2 中,您还可以使用 cmp
函数代替键,但这可能会使排序变慢.它是否会使它变得太慢取决于列表的大小和未排序.在 Python 3 中,cmp
参数消失了,但正如@Mark Ransom 指出的那样,您可以使用 cmp_to_key
.
In Python 2, you could also use a cmp
function instead of a key, but this will likely make the sort slower. Whether it will make it too slow depends on how big and unsorted the list is. In Python 3, the cmp
argument is gone, but as @Mark Ransom notes you could use cmp_to_key
.
这篇关于使用不同的顺序按多个键排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!