Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list with a custom order in Python

I have a list

mylist = [['123', 'BOOL', '234'], ['345', 'INT', '456'], ['567', 'DINT', '678']]

I want to sort it with the order of 1. DINT 2. INT 3. BOOL

Result:

[['567', 'DINT', '678'], ['345', 'INT', '456'], ['123', 'BOOL', '234']]

I've seen other similar questions in stackoverflow but nothing similar or easily applicable to me.

like image 925
elwc Avatar asked Jan 08 '13 04:01

elwc


People also ask

How do you sort a list in custom order in Python?

Using sort(), lamba, index(): The sort() function does the required in-place sorting(without creating a separate list to store the sorted order) along with a lambda function with a key to specify the function execution for each pair of tuples, the index() function helps to get the order from our custom list list_2.

How do you sort by order in Python?

Python List sort() - Sorts Ascending or Descending List. The list. sort() method sorts the elements of a list in ascending or descending order using the default < comparisons operator between items. Use the key parameter to pass the function name to be used for comparison instead of the default < operator.

What is the fastest way to sort a list in Python?

A best sorting algorithm in pythonQuicksort is also considered as the ” fastest” sorting algorithm because it has the best performance in the average case for most inputs.


2 Answers

SORT_ORDER = {"DINT": 0, "INT": 1, "BOOL": 2}  mylist.sort(key=lambda val: SORT_ORDER[val[1]]) 

All we are doing here is providing a new element to sort on by returning an integer for each element in the list rather than the whole list. We could use inline ternary expressions, but that would get a bit unwieldy.

like image 174
Sean Vieira Avatar answered Sep 23 '22 17:09

Sean Vieira


Another way could be; set your order in a list:

indx = [2,1,0] 

and create a new list with your order wished:

mylist = [mylist[_ind] for _ind in indx]  Out[2]: [['567', 'DINT', '678'], ['345', 'INT', '456'], ['123', 'BOOL', '234']] 
like image 27
Julio CamPlaz Avatar answered Sep 19 '22 17:09

Julio CamPlaz