Home > Blockchain >  Sort a list of strings using a user-provided order in Python
Sort a list of strings using a user-provided order in Python

Time:02-28

I have a list of strings, say ['ayyaaauu', 'shhasyhh', 'shaash'] and an accompanying order list ['s', 'y', 'u', 'h', 'a'].

I want to sort the list of strings using the order list in place of the normal alphabetical order used in sorting.

sorted(['ayyaaauu', 'shhasyhh', 'shaash']) would return ['ayyaaauu', 'shaash', 'shhasyhh'], sorting using alphabetical order.

I want the sort function to return ['shhasyhh', 'shaash', 'ayyaaauu'], which is the alphabet order specified in the order list.

Similar questions like this one are only useful if you only consider the first element of the string. I want to sequentially consider the entire string if the previous letters are the same.

P.S. In practice, I am generating the list of strings using letters from the order list, so all the letters in the strings have a "correct" order.

CodePudding user response:

You can use sorted(), and then generate the key parameter by using map() to map each letter to its priority (sorted() then uses tuple comparison to generate the ordering):

data = ['ayyaaauu', 'shhasyhh', 'shaash']
ordering = ['s', 'y', 'u', 'h', 'a']
priorities = {letter: index for index, letter in enumerate(ordering)}

result = sorted(data, key=lambda x: tuple(map(lambda y: priorities[y], x)))

# Prints ['shhasyhh', 'shaash', 'ayyaaauu']
print(result)
  • Related