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

时间:2019-06-03 18:46:49

标签: 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']

2 个答案:

答案 0 :(得分:6)

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

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

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

如果lst中存在任何order_list中不存在的字符,则会引发异常。

答案 1 :(得分:1)

您还可以使用dict来保持排序顺序:

someorder = {letter: val for val, letter in enumerate(order_list[0])}

# then use get on the dictionary for fast lookup
print(sorted(lst, key = lambda x: [someorder.get(letter) for letter in x]))

# ['AAA', 'AA1', 'AA2', 'AA3', 'A1', 'A2', 'A3', 'BBB1', 'BBB2', 'BBB3']

get处,您还可以为找不到的任何字符设置默认值:

default_value = max(someorder.values())+1
print(sorted(['A', 'BBB', 'X'], key = lambda x: [someorder.get(letter, default_value) for letter in x]))

# ['A', 'BBB', 'X']