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.

Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
  • Possible duplicate of [Sort a Python dictionary by value](http://stackoverflow.com/questions/613183/sort-a-python-dictionary-by-value) – sdasdadas Aug 17 '16 at 19:25

2 Answers2

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

Kenny Ostrom
  • 5,639
  • 2
  • 21
  • 30
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.

sethmlarson
  • 923
  • 8
  • 21
  • 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? –  Aug 17 '16 at 19:30
  • @CodeMonkey Have you tried running the code, at all? It uses the function you defined in your question to sort the list. – sethmlarson Aug 17 '16 at 19:31
  • Oasiscircle is doing that by calling the sorting function you already wrote. – Kenny Ostrom Aug 17 '16 at 19:33
  • I didn't realise the sorting was my sorting –  Aug 17 '16 at 19:37
  • 1
    @CodeMonkey Also note my edit to my answer, your comparison function does not work for what you want to achieve. – sethmlarson Aug 17 '16 at 19:37