Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list of lists by length and value in Python

How can I sort a Python list (with sublists)? For example, I have the following list:

list1 = [[0, 4, 1, 5], [3, 1, 5], [4, 0, 1, 5]]

After sorting I am expecting:

list1 = [[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]]

Another example. I have the following list:

list2 = [[4, 5, 2], [2, 5, 4], [2, 4, 5]]

After sorting I am expecting:

list2 = [[2, 4, 5], [2, 5, 4], [4, 5, 2]]

At first I want to sort by length, and then by itemwise in each sublist. I do not want to sort any sublist.

I have tried the following code, which helped me to sort by length only:

list1.sort(key=len)
like image 570
utij2004 Avatar asked Mar 21 '18 05:03

utij2004


1 Answers

You need a key like:

lambda l: (len(l), l)

How:

This uses a lambda to create a tuple which can the be used by sorted to sort in the desired fashion. This works because tuples sort element by element.

Test Code:

list1 = [[0, 4, 1, 5], [3, 1, 5], [4, 0, 1, 5]]
print(sorted(list1, key=lambda l: (len(l), l)))

list2 = [[4, 5, 2], [2, 5, 4], [2, 4, 5]]
print(sorted(list2, key=lambda l: (len(l), l)))

Results:

[[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]]
[[2, 4, 5], [2, 5, 4], [4, 5, 2]]
like image 135
Stephen Rauch Avatar answered Oct 22 '22 02:10

Stephen Rauch