lundi 31 août 2015

Python One-Liner: Sorting by multiple, interdepending keys

Disclaimer: This question is about me and hopefully others understanding Python better. My problem can be solved easily in more than one line, I know that.

Suppose I have two functions f(x), g(x,y) so that I can compute the tuple ( f(x), g(x,f(x)) ) as a function of x. I want to sort a list X by these two keys but computing f(x) is expensive so I want to do it only once per x. My current solution is:

X_s = sorted( X , key =  lambda x: (lambda y: ( y , g(x,y) ) )( f(x) ) )

Can I achieve the same without using two lambda functions?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire