1

I've written a sort in Python2, I'm trying to convert it into Python3 which asks for a key and says no more cmp function is available :

test.sort(lambda x, y: cmp(x[2],y[2]) or cmp(x[4], y[4]) or cmp(y[9], x[9]))

Any advices ?

Best regards,

5
  • At which point exactly are you stuck? Please edit your question accordingly refering to How do I ask a good question Commented Sep 18, 2018 at 11:20
  • 2
    Purely out of curiosity - what's that sort supposed to do? You're always going to end up with whatever the last comparison of elements 2, 4 or 9 aren't equal (either -1 or 1) or just 0 for equal... at the end... that seems almost randomly sorting to me. I have a feeling that's not a sort you wanted even if you could use it... are you sure what you're after as a key isn't just key=lambda L: (L[2], L[4], L[9]) so you get some sort of "order" there? Commented Sep 18, 2018 at 11:24
  • There are two separate problems here: 1) Finding a replacement for the cmp function, and 2) Making the sort work with a key= function. Those two separate problems have two separate answers, so in the future please ask about each problem individually. Commented Sep 18, 2018 at 11:35
  • What's the structure of test? Eg, is it a list of lists, or a list of tuples? Commented Sep 18, 2018 at 11:35
  • test is created into a loop like that : test.append((id, sexe, nom, prenom, date_naissance, telephone, sejour_id, etat, type, valeur)) Commented Sep 18, 2018 at 12:22

1 Answer 1

5

The official python 3 documentation explains in this section the proper way of converting this from python 2 to 3.

The original cmp function simply does something like

def cmp(x, y):
   if x == y:
       return 0
   elif x > y:
       return 1
   else:
       return -1

That is, it's equivalent to sign(x-y), but also supports strings and other data types.

However, your problem is that the current function of sort doesn't work with a comparison function with two arguments, but with a single key function of one argument. Python provides functools.cmp_to_key to help you convert it, so, do something like

test.sort(key = functools.cmp_to_key(
    lambda x, y: cmp(x[2],y[2]) or cmp(x[4], y[4]) or cmp(y[9], x[9])
)) 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.