38016226...@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. -- https://mail.python.org/mailman/listinfo/python-list