如何按特定顺序对python中字母和数字的字符串进行排序

Mal*_*Day 0 python

我有一个列表,希望按特定顺序进行排序。我已经尝试了来自stackoverflow的各种方法,但它们并没有为我提供所需的答案。任何帮助,将不胜感激

order_list = ['ABC123'] #this is the list that should define the order, according to the first character
lst = ['AA2', 'A3', 'A1', 'AA1', 'BBB2', 'A2', 'AA3', 'BBB1', 'AAA', 'BBB3']
print(sort_method(lst))

>>>['AAA', 'AA1', 'AA2', 'AA3', 'A1', 'A2', 'A3', 'BBB1', 'BBB2', 'BBB3','CCC1','CCC2']

#different orderlist
order_list = ['CBA123']
lst = ['BBB3', 'AA2', 'A2', 'BBB2', 'CCC2', 'AA3', 'CCC1', 'AAA', 'AA1', 'A3', 'BBB1', 'A1']
print(sort_method(lst))

>>>['CCC1','CCC2','BBB1', 'BBB2', 'BBB3','AAA', 'AA1', 'AA2', 'AA3', 'A1', 'A2', 'A3']
Run Code Online (Sandbox Code Playgroud)

myp*_*ion 6

无需在此处定义您自己的函数。stdlib函数sorted采用一个命名参数,key该参数可用于指定排序顺序。尝试这个:

print( sorted( lst, key=lambda x:[order_list[0].index(y) for y in x] ))
Run Code Online (Sandbox Code Playgroud)

key函数将根据要排序的字符串中每个字符的位置获取索引列表order_list

这将导致一个异常被抛出,如果任何字符存在于lst不存在的order_list