How do I sort a list in a given alphabetical order using python?

Inputs:

Alpha = ['d', 'c', 'a', 'b']
words = ['dda', 'bdb', 'adc', 'cdd']

      

How do I sort the words in Alpha order to get the next result?

words = ['dda', 'cdd', 'adc', 'bdb']

      

Could you please tell me how to do this?

Here I am trying to sort the list but not the dictionary keys

+3


source to share


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


you can use a sorted function with a key:



>>> Alpha = ['d', 'c', 'a', 'b']
>>> words = ['dda', 'bdb', 'adc', 'cdd']
>>> sorted(words, key=lambda x:Alpha.index(x[0]))
['dda', 'cdd', 'adc', 'bdb']

      

+1


source


You can use this, it will sort by the alpha index of the first letter.

alpha = ['d', 'c', 'a', 'b']
words = ['dda', 'bdb', 'adc', 'cdd']
words.sort(key=lambda x: alpha.index(x[0]))

      

Output:

"dda" "cdd" "adc" "bdb"

+1


source







All Articles