假设我有一个不同顺序的字母表:{H,V,R,L,D,A}。现在我想根据此顺序将字符串排序为 'HV'。我期待的应该是这样的:
$ alphabet = 'HVRLDA'
$ sorted(['RL','HH','AH'], key=lambda word: [alphabet.index(c) for c in word])
['HH','RL','AH']
这是一项已在 Sorting string values according to a custom alphabet in Python 中提到的任务.如果这些字符串之一包含此字母表之外的字符,脚本将中止并显示错误消息:
ValueError: substring not found
问题
我希望 Python 也根据 ASCII 码处理未出现的字符。从这个意义上说,其余的字母应该附加到这个字母表中。
感谢您的回复,我希望这个问题也能帮助到其他人。
请您参考如下方法:
如果字符不在 alphabet 中,您可以使用条件表达式只返回 c 的 ASCII 代码:
sort(['RL','HH','DA','AH'],
key=lambda word: [alphabet.index(c) if c in alphabet else ord(c) for c in word])
不过,我会为 alphabet 使用字典,因此您可以在此处使用 dict.get():
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])
从输入字符串生成字典非常简单:
alphabet = {c: i for i, c in enumerate(alphabet_string)}
