What's the proper way to write comparator as key in Python 3 for sorting? -


i'm not sure how write comparator in python 3 cmp parameter removed. considering following code in python 3, how rewrite comparator using 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.

this "comparison" function came inconsistent: should provide definite (deterministic) order, meaning, if change order of elements in list , run sorted - should same result!

in case, order of elements effects 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 "comparison" function inconsistent. first provide ordering function, should not difficult convert key function.


regards question raised in comments, key accepts function takes single argument - , returns "measurement" of "how big it". easiest example compare numbers, in case key function can be: lambda x: x. number lambda expression returns , comparison trivial!

modifying example:

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

a shorter version of above be:

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

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -