Lambda function in sort function

There is this code:

lista = [3,4,5,2,1,6,8,3] print lista # [3, 4, 5, 2, 1, 6, 8, 3] lista.sort(cmp=lambda x,y: cmp(y,x)) # sort descending print lista # [8, 6, 5, 4, 3, 3, 2, 1] -- it is sorted lista = [3,4,5,2,1,6,8,3] print lista # [3, 4, 5, 2, 1, 6, 8, 3] lista.sort(cmp=lambda x,y: y > x) # sort descending print lista # [3, 4, 5, 2, 1, 6, 8, 3] -- nothing happens 

Why doesn't the lambda function in the second block sort the numbers?

+4
source share
3 answers

The second example does not work, because the function you are passing is not a valid comparator.

Valid Comparator

returns a negative, zero, or positive number, depending on whether the first argument is considered smaller than, or greater than, the second argument.

The lambda x,y: y > x function does not fulfill this contract.

+19
source

The A cmp function should return a negative or positive number to indicate which element should go first (if they are not equal, then return 0). The function cmp y > x will only return 0 or 1 . Try changing it to the following:

 lista.sort(cmp=lambda x,y: (y > x) - (y < x)) 

I took this from the Python 3 docs :

If you really need cmp() functionality, you can use the expression (a > b) - (a < b) as the equivalent for cmp(a, b) .

+6
source

x <y returns True or False, and cmp returns 1 and -1. This code works:

 lista.sort(cmp=lambda x,y: 1 if x<y else -1) 
+2
source

Source: https://habr.com/ru/post/1385953/


All Articles