What is the correct way to write a comparator as a key in Python 3 for sorting?

I'm not sure how to write a comparator in Python 3 when removing the cmp parameter. Given the following code in Python 3, how do I rewrite a comparator using only the key?

import functools def my_cmp(x, y): return x*5-y*2 l = [50, 2, 1, 9] print(sorted(l, key=functools.cmp_to_key(my_cmp))) 

thanks.

+6
source share
1 answer

This "comparative" function that you encounter is incompatible: it must provide a certain (deterministic) order, that is, if you change the order of the items in the list and run sorted , you should get the same result!

In your case, the order of the elements affects the sorting:

 import functools def my_cmp(x, y): return x*5-y*2 l = [50, 2, 1, 9] print(sorted(l, key=functools.cmp_to_key(my_cmp))) # [2, 1, 9, 50] l = [50, 1, 2, 9] print(sorted(l, key=functools.cmp_to_key(my_cmp))) # [1, 2, 9, 50] 

which means your comparison function is incompatible. Provide a good ordering function first, so converting it to a key function is not very difficult.


Answering the question that you raised in the comments, key accepts a function that takes only one argument and returns a "dimension" of "how big it is." The simplest example is to compare numbers, in which case your key function might be simple: lambda x: x . For any number, the lambda expression will return itself, and the comparison is now trivial!

Change your example:

 def my_key(x): return xl = [50, 2, 1, 9] print(sorted(l, key=my_key)) # [1, 2, 9, 50] 

Shorter version above:

 l = [50, 2, 1, 9] print(sorted(l, key=lambda x: x)) # [1, 2, 9, 50] 
+1
source

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


All Articles