1

I want to sort lists of tuples of mathematical operators (stored as strings) and their index, in order of precedence (*,/,+,-), while retaining their original index. There are thousands of lists of tuples within my list.

E.g.

my_lists = [[(0,'*'),(1,'+'),(2,'-')],[(0,'-'),(1,'*'),(2,'*')],[(0,'+'),(1,'/'),(2,'-')]] 

should become:

new_list = [[(0,'*'),(1,'+'),(2,'-')],[(1,'*'),(2,'*'),(0,'-')],[(1,'/'),(0,'+'),(2,'-')]] 

I've tried using the 'sorted' built in function and storing the precedence in a dictionary.

priority = {'*': 0, '/': 1, '+': 2, '-': 3} new_list = [sorted(item, key = priority.get) for item in my_lists] 

This produces the same original list.

How do I access just the operator part of the tuple whilst sorting the list of tuples?

1
  • 4
    What did you try? Show your approach, and others may help you to get it done, but StackOverflow is not a coding service... Commented Jan 11, 2016 at 13:53

1 Answer 1

1

You are sorting using the whole tuple as key, such as (0, '*'). You have to use the second part of it only (i.e. x[1]):

[sorted(item, key = lambda x: priority.get(x[1])) for item in my_lists] 

returns

[[(0, '*'), (1, '+'), (2, '-')], [(1, '*'), (2, '*'), (0, '-')], [(1, '/'), (0, '+'), (2, '-')]] 

Your code didn't throw an error, because priority.get((0, '*')) is legal and returns None, which is perfectly sortable in Python 2.7 and keeps the list in its original order.

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

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.