Python按多个条件排序 [英] Python sorting by multiple criteria

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

问题描述

我有一个列表,其中每个元素的格式为[list of integers, integer]. 例如,列表的元素可能看起来像这样[[1,3,1,2], -1].

I have a list where each element is of the form [list of integers, integer]. For example, an element of the list may look like this [[1,3,1,2], -1].

我要按照以下条件对包含描述的元素类型的列表进行排序:

I want to sort a list containing the described type of elements by the following criteria:

  1. 如果两个元素的整数列表(即element[0])的长度不同,则整数列表较小的元素就是较小的元素.

  1. if the integer lists of two elements (i.e. element[0]) are of different length, the element with the smaller integer list is the smaller one.

否则,如果整数列表的长度相同,则较小的元素是第一个整数的较小整数,这两个元素的整数列表都不同.例如:

else if the integer lists are of the same length, the smaller element is that which has the smaller integer for the first integer which differs in the integer list of both elements. For example:

[[1,1,99,100],-1]< [[1,1,100,1],-1],因为99< 100.

[[1,1,99,100], -1] < [[1,1,100,1], -1], because 99 < 100.

否则,如果整数列表相同,则element[1]中较小的元素是整数较小的元素.

else if the integer lists are identical, the smaller element is the one with the smaller integer in element[1].

我如何编写可以传递给sorted()或sort()的适当键函数?

How would I write an approriate key function I could pass to sorted() or sort()?

推荐答案

在密钥中列出三个条件:

List the three criteria in your key:

sorted(inputlist, key=lambda e: (len(e[0]), e[0], e[1]))

现在,您要先按长度对每个元素进行排序,然后直接比较第一个元素(仅当第一个元素的长度相等时才使用),然后按最后一个整数的值进行排序.

Now you are sorting each element first by the length, then by comparing the first element directly (which in only used when the first element is of equal length), then by the value of the last integer.

Python按字典顺序对元组和列表进行排序;比较第一个元素,只有在没有区别的情况下,才比较第二个元素,依此类推.

Python sorts tuples and lists like these lexicographically; compare the first element, and only if that doesn't differ, compare the second element, etc.

这里的第二个元素是e[0],仅当两个比较的条目都具有相等长度的嵌套列表时才使用.再次按字典顺序对这些元素进行比较,因此将元素配对,直到一对不同为止.

The second element here is e[0] which will only be used if both compared entries have nested lists of equal length. These are again compared lexicographically, so pairing up elements until a pair differs.

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

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