50

Possible Duplicate:
python: how to sort a complex list on two different keys

I've got a list of tuples. I want to sort them depending two elements. Here is following example

unsorted = [('a', 4, 2), ('a', 4, 3), ('a', 7, 2), ('a', 7, 3), ('b', 4, 2), ('b', 4, 3), ('b', 7, 2), ('b', 7, 3)]
sorted   = [('a', 4, 2), ('b', 4, 2), ('a', 4, 3), ('b', 4, 3), ('a', 7, 2), ('b', 7, 2), ('a', 7, 3), ('b', 7, 3)]

I know how to sort them on the second element:

sorted(unsorted, key = lambda element : element[1])

But how to do that with two keys?

Community
  • 1
  • 1
Razer
  • 7,371
  • 15
  • 50
  • 98
  • 3
    The sorting done by Python is stable, meaning that you can in fact sort it twice, first on the least important element, then on the most important element. In certain cases this can in fact be faster (but only some times). – Lennart Regebro Feb 21 '12 at 19:58
  • https://stackoverflow.com/questions/4233476/sort-a-list-by-multiple-attributes – cardamom Mar 05 '19 at 15:26

1 Answers1

96
sorted(unsorted, key=lambda element: (element[1], element[2]))

I've assumed an order for the keys from the sample output.

Michael J. Barber
  • 23,704
  • 8
  • 64
  • 85