Python:按非字典顺序对字符串进行排序

Den*_*ost 2 python sorting

假设我有一个名为 sort_me 的列表,并且想要使用一个名为 special_alphabet 的非按字典顺序排列的字母表进行排序

sort_me = ['appa', 'apple', 'orange', 'carrot']
special_alphabet = "dklmnoabctuvwxyzfghipqrsej"

result = sorted(sort_me, key=?)
print (result)
Run Code Online (Sandbox Code Playgroud)

预期结果:['orange', 'apple', 'appa', 'carrot']

Vis*_*all 5

这是你可以做的

sorted(sort_me, key=lambda word: [special_alphabet.index(char) for char in word])
Run Code Online (Sandbox Code Playgroud)

输出

['orange', 'apple', 'appa', 'carrot']
Run Code Online (Sandbox Code Playgroud)

您可能想重新访问发布的预期输出,apple 将在 appa 之前,因为 l 在您的 special_alphabet 之前