How to sort lists in a list in a user-defined order?

I want to sort the lists of mathematical operators (stored as strings) in order of priority (*, /, +, -) in the list. There are thousands of listings on my list.

eg.

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

should become:

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

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

+4
source share
3 answers

You can define priority with a dictionary, for example

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

and then sort the individual lists with a value from priority, for example

>>> [sorted(item, key=priority.get) for item in my_lists]
[['*', '+', '-'], ['*', '*', '-'], ['/', '+', '-']]
+6
source

, ( ), key .

, key :

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

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

(*,/,+,-), , , @thefourtheye.

+6

key .sort().

:

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

, :

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

, dictionnary , :

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

Source: https://habr.com/ru/post/1623747/


All Articles