[How to Fix]Type error: must use keyword argument for key function

The reason may be the version problem of Python 2 and 3
chestnut 1: call sorted() and pass in reversed()_ CMP can achieve reverse order sorting

def reversed_cmp(x, y):
    if x > y:
        return 1
    if x < y:
        return -1
    return 0

L1 = [16, 5, 120, 9, 66]
print(sorted(L1, reversed_cmp))

terms of settlement:

L1 = [16, 5, 120, 9, 66]
print(sorted(L1, reverse=True))

The results were as follows

[120, 66, 16, 9, 5]

Maybe it’s too simple. Python doesn’t bother to use custom functions…
in continuous update...

Chestnut 2: using sorted() higher-order function to realize the algorithm of ignoring case sorting

def cmp_ignore_case(s1, s2):
    if s1[0].lower() > s2[0].lower():
        return -1
    if s1[0].lower() < s2[0].lower():
        return 1
    return 0

print(sorted(['haha', 'about', 'TIM', 'Credit'], cmp_ignore_case))

terms of settlement:

def com_flag(s):
    return s.lower()
# key represents the key function, the default is None, reverse represents whether to reverse the order, the default is False
# The following functions are arranged in reverse order
print(sorted(['haha', 'about', 'TIM', 'Credit'], key=com_flag, reverse=True))

The results were as follows

['Zoo', 'Credit', 'bob', 'about']

Read More: