gpt4 book ai didi

Python:根据不同的字母顺序排序

转载 作者:太空宇宙 更新时间:2023-11-04 07:08:37 25 4
gpt4 key购买 nike

假设我有一个不同顺序的字母表:{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)}

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com