Sort a list of tuples depending on two elements

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

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

Share:
58,138

Related videos on Youtube

Razer
Author by

Razer

Updated on July 09, 2022

Comments

  • Razer
    Razer almost 2 years

    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?

    • Lennart Regebro
      Lennart Regebro about 12 years
      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).
    • cardamom
      cardamom about 5 years
  • pod2metra
    pod2metra about 12 years
    May be sorted(unsorted, key=lambda element: (element[1:])) or sorted(unsorted, key=lambda element: (element[1:3])) is better
  • Michael J. Barber
    Michael J. Barber about 12 years
    @pod2metra There are numerous possibilities. Probably best would be operator.itemgetter(1,2).