python3 sorted in function cmp about change in this parameter

Today in the brush leetcode when the maximum number of returns for the 179 title, with python2 in sorted (cmp) will be very convenient, but in python3 in this parameter was canceled, after a search, found that the aid should functools in cmp_to_key function directly paste the code

import functools
def cmp(a,b):
    if a > b :
        return -1
    elif a < b :
        return 1
    else:
        return 0
        
nums = [1,2,3,4,5,6]
sorted_nums = sorted(nums, key = functools.cmp_to_key(cmp))

Out[30]: [6,5,4, 3, 2, 1]

But note cmp function return value to be converted must be 0, 1, -1

Guess you like

Origin www.cnblogs.com/ZAmateur/p/12467002.html