4

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?

1
  • Implement a comparator that you can later pass to the sorted method. Commented Jan 11, 2016 at 12:17

3 Answers 3

7

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]
[['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]
Sign up to request clarification or add additional context in comments.

Comments

6

The idea is to create a new list of operators and store the operators in the desired precedence you want(you may change the precedence anytime), and then use the index of operators as a key to do the sorting.

You may simply do it by passing a key to the sorted function as:

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

new_list = [sorted(i, key = operators.index) for i in my_lists]
>>> [['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]

however you mentioned a tuple in the question as (*,/,+,-), so I tried to solve the issue using list, but using a dictionary would be a cleaner way as @thefourtheye suggested.

3 Comments

You do not need to use lambda function: key=operators.index will work. ;)
The lists are small here. So it wouldn't be a big deal, but if the operators is a little lengthier, operators.index would eat up a lot of time.
As far as operators is concerned, I don't guess there would be hundreds of them :P, but anyways yours method is better, I admit.
2

You have to use the optional key argument of the .sort() method.

If you want to do this in-place:

for sublist in my_lists:
    sublist.sort(key="*/+-".index)

Or if you want to create a new list:

new_list = [sorted(sublist, key="*/+-".index) for sublist in my_lists]

Note that using dictionnary may be more efficient if you have many lists:

d = {"*": 0, "/": 1, "+": 2, "-": 3}
key = d.get

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.