2

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.

6
  • use ls.sort(key=functools.cmp_to_key(func)). sorted docs (list.sort refers to that) and functools docs Commented Jan 4, 2017 at 22:57
  • Thank you for your response. I tried now, but I received the message: "NameError: name 'functools' is not defined" Commented Jan 4, 2017 at 22:57
  • @PaulRooney: that's overkill for this sort. Commented Jan 4, 2017 at 23:02
  • true, I wasn't really looking at his code, just looking at how he could use what he had. Commented Jan 4, 2017 at 23:04
  • I added the import functools line and now I got the NameError: name 'cmp' is not defined again. Somehow the conversion doesn't work yet. Commented Jan 4, 2017 at 23:23

1 Answer 1

3

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.

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

8 Comments

hmm. I received an "IndexError: string index out of range" message for this code...
@Sam updated, I had missed your code is sorting based on an external mapping res.
Dear @Martijn Pieters : sorry, I didn't realize you edited your answer. Unfortunately, I am at the same point as before: "NameError: name 'cmp' is not defined" points to the line with val = cmp((w2,t2), (w1,t1)) :(
@Sam my answer doesn't use cmp at all. Remove all of func.
Ah, I see :) The problem is, that the program tries to call the func function later, and after I removed, I receive a "NameError: name 'func' is not defined" error message.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.