【发布时间】:2014-12-02 23:53:27
【问题描述】:
假设我有一个不同顺序的字母表:{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 码处理未出现的字符。从这个意义上说,其余的字母应该附加到这个字母表中。
感谢您的回复,希望这个问题也能对其他人有所帮助。
【问题讨论】:
标签: python python-2.7 sorting