Python:根据不同的字母顺序排序 [英] Python: Sorting according to a different alphabetic order
问题描述
假设我有一个字母,但顺序不同:{H,V,R,L,D,A}
.现在,我想根据此顺序将字符串作为'HV'
进行排序.我期待的东西看起来应该像这样:
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']
已根据Python中的自定义字母对字符串值进行排序中已经提到了这项任务.如果以下字符串之一包含此字母之外的字符,则脚本将中止并显示错误消息:
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
问题
我希望Python根据其ASCII代码也处理未出现的字符.从这个意义上讲,其余字母应附加到该字母上.
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.
推荐答案
如果在alphabet
中不存在该字符,则可以使用条件表达式返回c
的ASCII代码:
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])
但是,我会为alphabet
使用 dictionary ,因此,您可以在此处使用dict.get()
:
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)}
这篇关于Python:根据不同的字母顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!