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?
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]
[['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With