arr.sort(key = lambda x:(x [0],-x [1]))是什么意思? [英] What does arr.sort(key=lambda x: (x[0],-x[1])) mean?
本文介绍了arr.sort(key = lambda x:(x [0],-x [1]))是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
>>> arr=[[4,5],[4,6],[6,7],[2,3],[1,1]]
>>> arr.sort(key=lambda x:x[0]) #statement 1
>>> arr
[[1, 1], [2, 3], [4, 5], [4, 6], [6, 7]]
>>> arr.sort(key=lambda x:(x[0],-x[1])) #statement 2
>>> arr
[[1, 1], [2, 3], [4, 6], [4, 5], [6, 7]]
因此,我可以观察到语句1和语句2的执行之间的区别. 我知道语句1以x [0]的升序对列表进行排序. 但是,如果使用语句2,那么该列表如何排序?
So, I can observe the difference between the execution of statement 1 and statement 2. I am aware that statement 1 sorts the list in ascending order of x[0]. But if we use, statement 2 then how the list is sorted?
推荐答案
lambda x:(x[0],-x[1])
这将生成(第一个元素,第二个元素为负)的元组
this generates tuples of (the first element, negative of the second element)
当您对2元组进行排序时,它们将根据
When you sort 2-tuples, they are sorted based on
- 第一个元素
- 如果第一个元素相等,那么第二个元素
所以
arr.sort(key=lambda x:(x[0],-x[1]))
根据以下内容对列表arr
进行排序:
Sorts the list arr
based on:
- 第一个元素
- 如果第一个元素相等,则基于第二个元素的负数.
(这就是为什么[4,6]
从-6 < -5
开始在[4,5]
之前的原因)
(that is why [4,6]
is ahead of [4,5]
since -6 < -5
)
这篇关于arr.sort(key = lambda x:(x [0],-x [1]))是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文