1

I'm new to Python, thus the question,

I have the following list of list items,

[[0, 1], [2,3], [1,2], [4, 5], [3, 5]]

I want to sort this list in increasing order comparing the second item of each list first and then the first item

This is my code,

def sorting(a, b):
    if a[1] > b[1]:
        return 1
    elif a[1] == b[1]:
       if a[0] > b[0]:
            return 1
        else:
            return -1
    else:
        return 1

However can someone help me rewrite this using the sorted function with lambda and comprehensions.

1

2 Answers 2

1

You can reverse the order when the sort looks at them. Just don't alter the original list items.

sorted(l, key=lambda x: (x[1], x[0]))

Sign up to request clarification or add additional context in comments.

Comments

0

You should use Python's built-in sorted() method, it already has support for lambda comparisons.

l = [[0, 1], [2,3], [1,2], [4, 5], [3, 5]]
l = sorted(l, cmp=sorting)

Your comparison function is wrong if you want to sort in the way that you are talking about. There is no return zero case and the bottom return 1 should be return -1. Also indentation error.

5 Comments

Can you explain your answer a bit, I want to sort the list on the basis of the second number and then the first. How's this code doing that?
@CodeMonkey Have you tried running the code, at all? It uses the function you defined in your question to sort the list.
Oasiscircle is doing that by calling the sorting function you already wrote.
I didn't realise the sorting was my sorting
@CodeMonkey Also note my edit to my answer, your comparison function does not work for what you want to achieve.

Your Answer

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