How do I sort a list in a given alphabetical order using python?
3 answers
This will sort the words lexicographically based on your order listed in alpha
, by making a list of indices for each word (which Python then compares lexicographically )
def sort_key(w):
return [alpha.index(ch) for ch in w]
words.sort(key=sort_key)
There will probably be better solutions that store the key in a hash (as in the answer to this question ).
An alternative would be to turn yours alpha
into a conversion table string.translate
.
ascii_characters = ''.join(chr(i) for i in range(256))
translation = string.maketrans(''.join(alpha), ascii_characters[:len(alpha)])
words.sort(key=lambda w: w.translate(translation))
The advantage of this method is that you can put translations in the dictionary for (possibly) more speed.
order = {w: w.translate(translation) for w in words}
words.sort(key=lambda w: order[w]))
+1
source to share