假设我有一个不同顺序的字母表: {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 代码处理不出现的字符。从这个意义上说,其余的字母应该附加到这个字母表中。

感谢您的回复,我希望这个问题也能帮助其他人。

最佳答案

如果 c 中不存在该字符,您可以使用条件表达式仅返回 alphabet 的 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)}

关于Python:根据不同的字母顺序排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27253274/

10-12 20:04