How to sort this without 'cmp=' in python 3?
Mike H
michw6 at gmail.com
Tue Oct 24 20:58:25 EDT 2023
On Saturday, October 15, 2016 at 12:27:42 AM UTC-7, Peter Otten wrote:
> 38016... at gmail.com wrote:
>
> > 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?
> >
> > Thank you
> While cmp_to_key is neat doing it by hand should also be instructive.
> Essentially you move the comparison into a method of the key:
>
> $ cat translate_cmp.py
> class Key(str):
> def __lt__(a, b):
> return a + b < b + a
>
> nums = ['3','30','34','32','9','5']
> print(nums)
> nums.sort(key=Key, reverse=True)
> print(nums)
> print("".join(nums))
>
> $ python3 translate_cmp.py
> ['3', '30', '34', '32', '9', '5']
> ['9', '5', '34', '3', '32', '30']
> 953433230
>
> The above works because in CPython list.sort() currently uses only the <
> operator; adding __gt__() and __eq__() to make this portable is
> straightforward even if you do not use the functools.total_ordering class
> decorator.
Is it possible to use lambda expression instead of defining a `Key` class? Something like `sorted(my_list, key = lambda x, y: x+y > y+x)`?
More information about the Python-list
mailing list