4

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.

1
  • 4
    list.sort(key=lambda x: x[::-1])? Commented Jul 7, 2018 at 4:57

2 Answers 2

5

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]]
Sign up to request clarification or add additional context in comments.

1 Comment

In your answer you fixed it to second digit, i want to sort it by looking from end if last digits are same then it should look at second last digit.
3

You can try:

sorted(a,key=lambda a:list(reversed(a)))

Output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.