Sort a list with a custom order in Python

19,467

Solution 1

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.

Solution 2

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']]
Share:
19,467
elwc
Author by

elwc

Updated on June 02, 2022

Comments

  • elwc
    elwc almost 2 years

    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.