1

How do I sort a list consisting of (int, string)-pairs descending by int and ascending by string?

cspecial
  • 89
  • 9
  • 1
    Please provide a [mcve] including sample input, sample output, and _code_ for what you've already tried based on your own research – G. Anderson Jan 10 '20 at 18:18
  • 1
    This question might be of help for scenarios like this one: https://stackoverflow.com/questions/11476371/sort-by-multiple-keys-using-different-orderings – MkWTF Jan 10 '20 at 18:21

1 Answers1

2

You can use sorted with a custom key argument. In this case negating the int will cause a descending behavior, then leave the str which will cause ascending behavior. Putting them in a tuple will allow lexicographical sort behavior if the first key (int) is identical.

>>> data = [(1, 'hello'), (7, 'bar'), (4, 'foo'), (4, 'world')]
>>> sorted(data, key=lambda i: (-i[0], i[1]))
[(7, 'bar'), (4, 'foo'), (4, 'world'), (1, 'hello')]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218