1

Say I have a list composed of a number of lists of two items each:

a = [[14, 0.5], [12, 0.8], [22, 0.6], [15, 0.2], [17, 0.5], [18, 0.4]]

I need to reorder this list first according to the second items inside each list from max to min and then according to the first items from min to max.

I know how to reorder a list according to two items using the second item first and the first item second:

b = sorted(a, key=lambda item:(item[1], item[0]))
b = [[15, 0.2], [18, 0.4], [14, 0.5], [17, 0.5], [22, 0.6], [12, 0.8]]

but this returns a list ordered from min to max for both items, which is not what I need.

This is what b should look like:

b = [[12, 0.8], [22, 0.6], [14, 0.5], [17, 0.5], [18, 0.4], [15, 0.2]]
Gabriel
  • 40,504
  • 73
  • 230
  • 404

2 Answers2

6

You can use the negative value:

b = sorted(a, key=lambda item:(-item[1], item[0]))
w-m
  • 10,772
  • 1
  • 42
  • 49
4

Just use the negation of the item which you want in reverse:

>>> b = sorted(a, key=lambda item:(-item[1], item[0]))
>>> b
[[12, 0.8], [22, 0.6], [14, 0.5], [17, 0.5], [18, 0.4], [15, 0.2]]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • Since you and w.m both answered the same thing at pretty much the same time, I marked his answer as accepted to boost his reputation a bit (you have a lot! :). Thank you both! – Gabriel Jul 30 '13 at 13:47
  • @Gabriel. haha. I like your reasoning. :) But really, no need of that. And you're welcome :) – Rohit Jain Jul 30 '13 at 14:01