简体   繁体   中英

Python: Sorting according to a different alphabetic order

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

Question

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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM