python sort parameter lambda function key and

First, lambda format the lambda X: X +. 1 ,

X corresponds to the front of the incoming parameter , the latter corresponding to the return value ,

It is simple to use, as long as the clear ":" meaning before and after can be used correctly.

Let me now look key functions such as sorting, here to list.sort (key = ??), for example,

If the list = [1, -2, 3 , -4, 5], then list.sort (key = lambda x: x * -1)

After execution list becomes [5, 3, 1, -2, -4], ( note that , although there appears to be no problem in descending order,

But sort default ascending arranged)

It is easy to see that this sort function iterates over the list, traversing each process in accordance with the

In contrast corresponding to the number of items are sorted, the key can be abstracted as a parameter added to each

A representative of value "height", and then sort the list according to the original value.

So, key passed in is actually a handler, then the value sorted according to post-processing .

Guess you like

Origin www.cnblogs.com/ligaofeng/p/11945957.html