0

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']
3
  • please show us your code for this method: sort_method Commented Jun 3, 2019 at 18:49
  • In addition to showing us your sort_method, what results are you expecting? This seems correct based on the order described. Commented Jun 3, 2019 at 18:51
  • As far as I can see, order_list is never used... Commented Jun 3, 2019 at 18:51

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.