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.
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]]
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