headache headache - 8 months ago 30
Python Question

Sort a list by multiple attributes?

I have a list of lists (which could have been tuples, but I digress) in a format such as:

[12, 'tall', 'blue', 1]
[15, 'tall', 'black', 3]
[13, 'tall', 'blue', 8]
[9, 'short', 'blue', 3]
[1, 'short', 'black', 2]
[2, 'short', 'red', 9]
[4, 'tall', 'blue', 13]

If I wanted to sort by one element, say the tall/short element, I could do it via
s = sorted(s, key = itemgetter(1))

If I wanted to sort by BOTH tall/short and colour, I could do the sort twice. Once for each element. However, this is computationally ridiculous. Is there a quicker way?


A key can be a function that returns a tuple:

s = sorted(s, key = lambda x: (x[1], x[2]))

Or you can achieve the same using itemgetter:

import operator
s = sorted(s, key = operator.itemgetter(1, 2))

And notice that here you can use sort instead of using sorted and then reassigning:

s.sort(key = operator.itemgetter(1, 2))