Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list by multiple attributes?

Tags:

python

sorting

I have a list of lists:

[[12, 'tall', 'blue', 1], [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, but is there a quicker way?

like image 407
headache Avatar asked Nov 20 '10 15:11

headache


People also ask

Can you sort a list with different data types?

Python does not guarantee that the sort() function will work if a list contains items of different data types. As long as the items can be compared using the < comparison operator, an attempt will be made to sort the list. Otherwise, an error or exception may be generated.


1 Answers

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 (which is faster and avoids a Python function call):

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)) 
like image 121
Mark Byers Avatar answered Oct 12 '22 03:10

Mark Byers