Sort a list with a custom order in Python

Question:

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.

Asked By: elwc

||

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.

Answered By: Sean Vieira

Since that is not in aphabetical order I don’t think there is one single function that can sort it but what you could do is create a new list and then append. This is kind of a cheap method of doing it; but it gets the job done.

newlist=[];
for sub_list in mylist:
     if(sub_list[1] == 'DINT']):
          newlist.append(sub_list);

for sub_list in mylist:
     if(sub_list[1] == 'INT']):
         newlist.append(sub_list);

for sub_list in mylist:
     if(sub_list[1] == 'BOOL']):
            newlist.append(sub_list);
Answered By: Devon Bernard
     python 3.2

    1. sorted(mylist,key=lambda x:x[1][1])

    2. sorted(mylist,reverse=True)
Answered By: raton

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']]
Answered By: Julio CamPlaz

You can define an explicit order by a list:

def explicit_order(xs):
    """Return a key function that, when passed to sort or sorted, will sort
    the elements in the order they appear in this list.
    """
    keys = {x: i for i, x in enumerate(xs)}
    def key_function(x):
        return keys[x]
    return key_function

order = explicit_order(['DINT', 'INT', 'BOOL'])
sorted(['BOOL', 'INT'], key=order) # = ['INT', 'BOOL']

Since in your example you also have to extract the string from your tuples, you’ll have a slightly more complex key-function:

sorted(mylist, key=lambda x: order(x[1]))
Answered By: MikeFHay
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.