How to sort this without 'cmp=' in python 3?

Ned Batchelder ned at nedbatchelder.com
Fri Oct 14 19:57:57 EDT 2016


On Friday, October 14, 2016 at 7:49:33 PM UTC-4, Robin Koch wrote:
> Am 15.10.2016 um 01:33 schrieb 380162267qq at gmail.com:
> > nums=['3','30','34','32','9','5']
> > I need to sort the list in order to get the largest number string: '953433230'
> >
> > nums.sort(cmp=lambda a,b: cmp(a+b, b+a), reverse=True)
> >
> > But how to do this in python 3?
> 
> https://docs.python.org/3/library/functools.html#functools.cmp_to_key
> 
> | Transform an old-style comparison function to a key function.

cmp_to_key is a neat magic trick of a function, because it's seemingly
doing the impossible: how can a two-argument function be turned into 
a one-argument function?

Studying the code turns up a few clever Python tricks.

--Ned.



More information about the Python-list mailing list