2

I am trying to create a program that orders a list of words with my choice of alphabetical order, but I am a little confused with how to begin.

For instance, if the chosen alphabetical order was: UVWXYZNOPQRSTHIJKLMABCDEFG Then words would be sorted in this order:

  • WHATEVER
  • ZONE
  • HOW
  • HOWEVER
  • HILL
  • ANY
  • ANTLER
  • COW
star
  • 179
  • 1
  • 1
  • 6

1 Answers1

3

You can use a sort key that maps letters to a list of integers, the integers being in order in which to sort:

sort_key = {l: i for i, l in enumerate('UVWXYZNOPQRSTHIJKLMABCDEFG')}
sorted_words = sorted(words, key=lambda w: [sort_key[l] for l in w])

Lists are ordered lexicographically, that is, by comparing the elements of two lists one by one until a differing element is found, which then determines the order. For the words 'ANTLER' and 'ANY' are mapped to [19, 6, 12, 17, 23, 10] and [19, 6, 4], respectively, so 'ANY' will be listed first as 4 < 10.

Demo:

>>> words = ['ANTLER', 'ANY', 'COW', 'HILL', 'HOW', 'HOWEVER', 'WHATEVER', 'ZONE']
>>> sort_key = {l: i for i, l in enumerate('UVWXYZNOPQRSTHIJKLMABCDEFG')}
>>> sorted(words, key=lambda w: [sort_key[l] for l in w])
['WHATEVER', 'ZONE', 'HOW', 'HOWEVER', 'HILL', 'ANY', 'ANTLER', 'COW']
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343