Sorting function in Python 3


I would like to use an older python script with cmp function, but it doesn't work in Python 3. It raises an error:

TypeError: must use keyword argument for key function 

I know that I should avoid the cmp function and use the key function instead, but I don't know how (I don't know Python and I am not a programmer). Could you please help me to change the following part according to this?

ls = list(self.entries)

def func(key1, key2):
    (w1,l1,t1) = res[key1]
    (w2,l2,t2) = res[key2]
    val = cmp((w2,t2), (w1,t1))
    return val

Thank you.

Show source
| sorting   | python   | python-3.x   2017-01-04 23:01 1 Answers

Answers to Sorting function in Python 3 ( 1 )

  1. 2017-01-05 00:01

    Just return the first and last element of each tuple you are sorting, but reverse the result:

    ls.sort(key=lambda t: (res[t][0], res[t][2]), reverse=True)

    That's exactly what the cmp version was comparing on, but in reverse, and the sort() method will do so too.

Leave a reply to - Sorting function in Python 3

◀ Go back