0

I am trying to sort a list of lists in python based on certain criteria:

The comparison can be written as:

def cmp(item1, item2):
    """
    item1 and item 2 would be lists
    """
    # Second field is equal, compare on first field
    if item1[0][2] == item2[0][2]:
        if item1[0][1] > item2[0][1]:    
            return 1
        elif item1[0][1] == item2[0][1]:     
            return 0
        else:
            return -1
    else:  # Compare on second field
        if item1[0][2] > item2[0][2]:    
           return 1
        elif item1[0][2] == item2[0][2]:     
            return 0
        else:
            return -1

In python 3, there is a key parameter that can be used for sorting. I wonder how I can specify this function to be used for sorting like python 2.x versions.

Luca
  • 10,458
  • 24
  • 107
  • 234
  • There is also a key parameter in python2, are you asking how to do cmp in python3? i.e https://docs.python.org/3/library/functools.html#functools.cmp_to_key – Padraic Cunningham Oct 21 '16 at 16:42
  • @PadraicCunningham Yes, I did not word it very clearly. – Luca Oct 21 '16 at 16:43
  • 1
    Then ^^ functools.cmp_to_key will do the job – Padraic Cunningham Oct 21 '16 at 16:44
  • 3
    this seems the key function `lambda item: return (item[0][2], item[0][1])` would do the trick ... – mgilson Oct 21 '16 at 16:46
  • Why do you want to use cmp-based sorting? Looks like you can easily do key-based sorting there, no? – Stefan Pochmann Oct 21 '16 at 16:46
  • @StefanPochmann The key based stuff I could not figure out how to write it as a lambda because I have this first check for equality and the control paths based on that.. – Luca Oct 21 '16 at 16:47
  • 1
    @luca you want to first compare elements based on `item[0][2]` then if they are the same compare based on `item[0][1]`, tuples have comparison set up so it compares the first element and if they are equal it then checks the next etc. so using the key function suggested by @mgilson would do exactly what you want in this case. – Tadhg McDonald-Jensen Oct 21 '16 at 16:50

0 Answers0