Assume I have an alphabet with a different order: {H,V,R,L,D,A}. Now I want to order strings as 'HV' according to this order. I was expecting something that should look like:
$ alphabet = 'HVRLDA'
$ sorted(['RL','HH','AH'], key=lambda word: [alphabet.index(c) for c in word])
['HH','RL','AH']
This is a task that was mentioned already in Sorting string values according to a custom alphabet in Python. If one of these strings contains a character outside this alphabet, the script aborts with the error message:
ValueError: substring not found
I want Python to process also non appearing characters according to their ASCII code. In this sense the rest of the letters should be appended to this alphabet.
Thank you for your replies and I hope this question could help others too.
You can use a conditional expression to just return the ASCII code for c if the character is not present in alphabet:
sort(['RL','HH','DA','AH'],
key=lambda word: [alphabet.index(c) if c in alphabet else ord(c) for c in word])
I'd use a dictionary for alphabet instead, however, so you can use dict.get() here:
alphabet = {'H': 0, 'V': 1, 'R': 2, 'L': 3, 'D': 4, 'A': 5}
sort(['RL','HH','DA','AH'],
key=lambda word: [alphabet.get(c, ord(c)) for c in word])
Producing that dictionary from an input string is easy enough:
alphabet = {c: i for i, c in enumerate(alphabet_string)}
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