Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19k points)

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?

1 Answer

0 votes
by (106k points)

We have many ways to sort a list by multiple attributes the first thing you can do is use a key in the function which returns a tuple below is the code for the same:

abc=[[12, 'tall', 'blue', 1],[2, 'short', 'red', 9],[4, 'tall', 'blue', 13]]

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

print(s)

image

Or you can achieve the same using itemgetter (which is faster and avoids a Python function call):

import operator

abc=[[12, 'tall', 'blue', 1],[2, 'short', 'red', 9],[4, 'tall', 'blue', 13]]

s = sorted(abc, key = operator.itemgetter(1, 2, 3)) print(s)

image

Related questions

0 votes
1 answer
asked Jul 10, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
2 answers
+1 vote
1 answer
0 votes
1 answer

Browse Categories

...