Reputation: 69
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.
Upvotes: 4
Views: 206
Reputation: 195438
You can try:
sorted(a,key=lambda a:list(reversed(a)))
Output:
[[9, 7, 2, 2], [1, 8, 2, 2], [2, 9, 2, 2]]
Upvotes: 3
Reputation: 562
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]]
Upvotes: 5