-1

(Using Python 3)

I want to sort a list of lists by the values and the string in the smaller list and print them like so:

(This is just a simplified example of what I'm trying to do) a 4 a 3 b 3 c 3 a 2 b 2 c 2 d 2 a 1 b 1 c 1 d 1

In my code i used

my_list = sorted(mylist, key=itemgetter(1), reverse=True)

and obtained something like

[['a', 4], ['c', 3], ['b', 3], ['a', 3], ['d', 2], ['c', 2], ['b', 2], ['a', 2], ['d', 1], ['c', 1], ['b', 1], ['a', 1]]

As you can see my values are decreasing like I want them. However, the strings in the smaller lists that have the same value are in anti-alphabetical order.

Any suggestions?

Levi Baguley
  • 646
  • 1
  • 11
  • 18

1 Answers1

0

Python uses a stable sort so for ties, items will show up in the same order they occurred. You can sort on multiple keys, but that will reverse the sort for both:

my_list = sorted(mylist, key=itemgetter(1, 0), reverse=True)

or sort twice since you only want one of the sorts reversed:

my_list = sorted(sorted(my_list, key=itemgetter(0)), key=itemgetter(1), reverse=True)
avigil
  • 2,218
  • 11
  • 18