Inputs:
Alpha = ['d', 'c', 'a', 'b']
words = ['dda', 'bdb', 'adc', 'cdd']
How do I sort words in the order of Alpha to get the following result?
words = ['dda', 'cdd', 'adc', 'bdb']
Could you please me on how to do this?
Here I am trying to sort a list but not the dictionary keys
This will sort the words lexicographically based on your order specified 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 are likely to be more efficient solutions that store the key in a hash (as in the answer to this question).
An alternative would be to turn your alpha into a string.translate translation table.
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))
An advantage of this way is that you can put the translations into a dictionary for (possibly) greater speed.
order = {w: w.translate(translation) for w in words}
words.sort(key=lambda w: order[w]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With