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)
You need a key like:
lambda l: (len(l), l)
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.
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)))
[[3, 1, 5], [0, 4, 1, 5], [4, 0, 1, 5]]
[[2, 4, 5], [2, 5, 4], [4, 5, 2]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With