简体   繁体   English

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

[英]How to sort strings with letters and numbers in python by a specific order

I have a list that I want to be sorted in a specific order. 我有一个列表,希望按特定顺序进行排序。 I have tried various methods from stackoverflow, and they are not getting me the answer I need. 我已经尝试了来自stackoverflow的各种方法,但它们并没有为我提供所需的答案。 Any help would be appreciated 任何帮助,将不胜感激

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']

There's no need to define your own function here. 无需在此处定义您自己的函数。 The stdlib function sorted takes a named parameter, key that can be used to specify the sort order. sorted的stdlib函数采用一个命名参数,该key可用于指定排序顺序。 Try this: 尝试这个:

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

The key function will get a list of indexes for each character in the strings to be sorted, based on that character's position in the order_list . key函数将基于要排序的字符串中每个字符在order_list的位置获取索引列表。

This will cause an exception to be thrown if any characters are present in lst that are not present in order_list . 如果lst中存在不存在于order_list任何字符,则将引发异常。

You could also use a dict to keep the sorting order: 您还可以使用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']

Where get will also allow you to put a default in for any characters that aren't found: 在哪里, 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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM