Python 对 Lambda 进行排序

Python Sort Lambda

对关键 Lambda 参数进行排序

我不明白 lambda 参数是如何工作的,[-e[0],e[1]] 部分特别令人困惑。我已经删除了所有多余的打印代码,并且还从我的问题中删除了所有不必要的代码。参数-e[0]的作用是什么,e[1]的作用是什么?

data.sort(key = lambda e: [-e[0],e[1]]) # --> anonymous function
print ("This is the data sort after the lambda filter but NOT -e %s" %data)`

[in] 'aeeccccbbbbwwzzzwww'
[out] This is the data before the sort [[2, 'e'], [4, 'c'], [1, 'a'], [4, 'b'], [5, 'w'], [3, 'z']]
[out] This is the data sort before the lambda filter [[1, 'a'], [2, 'e'], [3, 'z'], [4, 'b'], [4, 'c'], [5, 'w']]
[out] This is the data sort after the lambda filter but NOT -e [[1, 'a'], [2, 'e'], [3, 'z'], [4, 'b'], [4, 'c'], [5, 'w']]
[out] This is the data sort after the lambda filter [[5, 'w'], [4, 'b'], [4, 'c'], [3, 'z'], [2, 'e'], [1, 'a']]

[out] w 5
[out] b 4
[out] c 4

l = [[2, 'e'], [4, 'c'], [1, 'a'], [4, 'b'], [5 , 'w'], [3, 'z']]

>>> l.sort()

正常排序:首先考虑嵌套列表的第一个元素,然后是第二个元素。

>>>l.sort(key=lambda e: [e[0], e[1]])

类似于l.sort()

>>>l.sort(key=lambda e: [-e[0], e[1]])

现在,要做的是-根据嵌套列表的第一个元素对列表进行反向排序,然后对嵌套排序列表的内部元素进行正常排序,即

首先考虑 2、3、4、5 等以倒序对列表进行排序(-e[0] == -2、-3、-4...),然后我们对元素进行排序内部排序的第二个元素的基础 (e[1] == 'w', 'a', 'b'...)