0

I want to sort, let's say, this list:

[('alpha', 2), ('delta', 3), ('charlie', 3), ('tango', 1), ('foxtrot', 1), ('echo', 2)]

The result should be

[('charlie', 3), ('delta', 3), ('alpha', 2), ('echo', 2), ('foxtrot', 1), ('tango', 1)]

charlie is first because it has the largest number, and it's ahead of delta because c alphabetically comes before d (so if the numbers are the same it sorts those specific ones alphabetically). alpha is ahead of echo because even though they have the same number, a alphabetically comes before e. echo is ahead of foxtrot because echo has the larger number, and foxtrot is ahead of tango even though they have the same number because f comes before t.

Currently my method involves a while loop (which moves the item to the right spot) inside of a for loop (which looks at every element), with another loop afterwards that does the same thing if the number is the same so it can sort alphabetically.

Is there a better method of doing this?

EvanKing
  • 11
  • 3
  • The `sorted` function does this: `sorted(mylist, key=lambda x: (-x[1], x[0]))` - looking for a dupe. – pault Dec 03 '19 at 19:11
  • 1
    Sorting [HOWTO](https://docs.python.org/3/howto/sorting.html), possible dupes: https://stackoverflow.com/questions/222752/sorting-a-tuple-that-contains-tuples, https://stackoverflow.com/questions/403421/how-to-sort-a-list-of-objects-based-on-an-attribute-of-the-objects, https://stackoverflow.com/questions/327191/is-there-a-one-liner-way-to-get-a-list-of-keys-from-a-dictionary-in-sorted-ord – Bahrom Dec 03 '19 at 19:12

1 Answers1

1

You can write your own key to pass to sorted. In this case, first sort by the [1] index, but negate it so you get descending order. Then sort by name in ascending alphabetical order, which is index [0].

>>> sorted(values, key=lambda i: (-i[1], i[0]))
[('charlie', 3), ('delta', 3), ('alpha', 2), ('echo', 2), ('foxtrot', 1), ('tango', 1)]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218