Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting a 2D list in Python

I have a 2D list:

mylist = [[9,7, 2, 2], [1,8, 2, 2], [2,9, 2, 2]]

Using a sort function, the list is sorted like this:

[[1, 8, 2, 2], [2, 9, 2, 2], [9, 7, 2, 2]]

But I want to sort this list like this:

[[9, 7, 2, 2],[1, 8, 2, 2], [2, 9, 2, 2]]

in which instead of the first digit of the list, I want to sort it by the last digit, like using a sort function - it sorted by the first digit of the list. I want to sort it by the last digit like 7 is smaller than 8 and 9 so 7 comes first.

like image 800
tarunsharma967 Avatar asked Jan 28 '23 19:01

tarunsharma967


1 Answers

use sorted() with lambda Try this

In [1]: a=[[9, 7, 2, 2],[1, 8, 2, 2], [2, 9, 2, 2]]
In [4]: sorted(a,key=lambda a:a[::-1])
Out[4]: [[9, 7, 2, 2], [1, 8, 2, 2], [2, 9, 2, 2]]
like image 164
Nidhin Sajeev Avatar answered Jan 30 '23 09:01

Nidhin Sajeev