Sam
Sam

Reputation: 23

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
ls.sort(func)

Thank you.

Upvotes: 2

Views: 806

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121634

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.

Upvotes: 3

Related Questions