Python3 removed the cmp parameter which was used for comparison during sorting and replaced it with key.
The cmp_to_key function was introduced to be "primarily used as a transition tool for programs being converted from Python 2".
It is unclear to me how to recreate cmp behavior natively in python3 with key. For example, if I want to sort strings by length, with a tie-breaker by lexicographic order, I would write something like this:
def compare(word1, word2):
if len(word1) > len(word2):
return 1
if len(word2) > len(word1):
return -1
if word1 < word2:
return 1
if word2 < word1:
return -1
return 0
myStrings.sort(key=functools.cmp_to_key(compare), reverse=True)
How can a comparison across objects be done in a python3-native way, meaning without cmp_to_key?
One thing I can think of is returning a more complex key, for example:
# This would return something like 5.12 for "hello" and 5.20 for "world"
def myKey(word):
return len(word) + myLexicographicalValueFunction(word)/100
myStrings.sort(key=myKey, reverse=True)
But this doesn't seem to scale well as you add more variables to compare. What is a pythonic way of using multiple fields for key evaluation during sorting in python3?