-1

I need to sort something like

list = [('B', 2), ('A', 6), ('D', 4), ('E', 6), ('C', 2)]

into:

sorted_list = [('A', 6), ('E', 6), ('D', 4), ('B', 2), ('C', 2)]

So it is first sorted from the tuple with the highest number first, then if the numbers are equal, the tuples are sorted alphabetically by the letter in the first element.

So priority is highest to lowest in terms of the numbers in each tuple, then alphabetically if 2 or more values are equal.

  • Does this answer your question? [Sort a list by multiple attributes?](https://stackoverflow.com/questions/4233476/sort-a-list-by-multiple-attributes) – DarrylG May 09 '20 at 10:57

2 Answers2

0

You can do it like this:

sorted([('B', 2), ('A', 6), ('D', 4), ('E', 6), ('C', 2)], key = lambda x: (-x[1],x[0]))

yields:

[('A', 6), ('E', 6), ('D', 4), ('B', 2), ('C', 2)]
Christian Sloper
  • 7,440
  • 3
  • 15
  • 28
0
a = [('B', 2), ('A', 6), ('D', 4), ('E', 6), ('C', 2)]
print sorted(a, key=lambda tup: tup[1], reverse=True)

will print [('A', 6), ('E', 6), ('D', 4), ('B', 2), ('C', 2)]

Gal
  • 504
  • 4
  • 11