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

    From Mike H@21:1/5 to Peter Otten on Tue Oct 24 17:58:25 2023
    On Saturday, October 15, 2016 at 12:27:42 AM UTC-7, Peter Otten wrote:
    38016...@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)`?

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)
  • From Chris Angelico@21:1/5 to python-list@python.org on Wed Oct 25 13:12:01 2023
    On Wed, 25 Oct 2023 at 13:02, Mike H via Python-list
    <python-list@python.org> wrote:
    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)`?

    Look up functools.cmp_to_key.

    ChrisA

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)