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

Peter Otten __peter__ at web.de
Sat Oct 15 03:26:51 EDT 2016


380162267qq 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.





More information about the Python-list mailing list