【问题标题】:Python: Sorting according to a different alphabetic orderPython:根据不同的字母顺序排序
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 非常好,它也像预期的那样区分大小写。字典的优势及其与字母表的区别是什么?
    • 或者为了好玩,alphabet = dict(zip(alphabet_string, itertools.count()))。您甚至可以从负数开始,只是为了涵盖字母表中的字符比要排序的字符串中任何其他字符的最小数值更多的情况。
    猜你喜欢
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多