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?