How to use a custom comparison function in Python 3?
Use the key
keyword and functools.cmp_to_key to transform your comparison function:
sorted(x, key=functools.cmp_to_key(customsort))
Use the key
argument (and follow the recipe on how to convert your old cmp
function to a key
function).
functools
has a function cmp_to_key
mentioned at docs.python.org/3.6/library/functools.html#functools.cmp_to_key
Instead of a customsort(), you need a function that translates each word into something that Python already knows how to sort. For example, you could translate each word into a list of numbers where each number represents where each letter occurs in your alphabet. Something like this:
my_alphabet = ['a', 'b', 'c']def custom_key(word): numbers = [] for letter in word: numbers.append(my_alphabet.index(letter)) return numbersx=['cbaba', 'ababa', 'bbaa']x.sort(key=custom_key)
Since your language includes multi-character letters, your custom_key function will obviously need to be more complicated. That should give you the general idea though.