Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort lists within list in user defined order?

I want to sort lists of mathematical operators (stored as strings) in order of precedence (*,/,+,-) within a list. There are thousands of lists within my list.

E.g.

my_lists = [['*','+','-'],['-','*','*'],['+','/','-']]

should become:

new_list = [['*','+','-'],['*','*','-'],['/','+','-']]

Is there a way to sort the lists within my list in a user defined order?

like image 288
jcdrbm Avatar asked Dec 05 '22 19:12

jcdrbm


1 Answers

You can define the priority with a dictionary, like this

>>> priority = {'*': 0, '/': 1, '+': 2, '-': 3}

and then sort the individual lists, with the value from the priority, like this

>>> [sorted(item, key=priority.get) for item in my_lists]
[['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]
like image 79
thefourtheye Avatar answered Dec 13 '22 21:12

thefourtheye