python sort 多级排序,Python按多个条件排序

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:

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], because 99 < 100.

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

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 sorts tuples and lists like these lexicographically; compare the first element, and only if that doesn't differ, compare the second element, etc.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值