对键 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'...)
关于Python 排序 Lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32167725/