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. 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. 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
.
This will cause an exception to be thrown if any characters are present in lst
that are not present in order_list
.
You could also use a dict
to keep the sorting order:
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:
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']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.