Python Sort One List According to Another List

list, python, sorting

Solution

First, I'd make `colorOrder` a mapping:

colorMap = {c: i for i, c in enumerate(colorOrder)}

Now sorting becomes a bit easier with `colorMap.get`

sorted(tupleList, key=lambda tup: colorMap.get(tup[1], -1))

This puts things not in the map first. If you'd rather add them last, just use a really big number:

sorted(tupleList, key=lambda tup: colorMap.get(tup[1], float('inf')))

Problem

I have two lists, the first list is the key order, the second list is a tuple list. ``` colorOrder = ['red', 'blue', 'yellow', 'green'] tupleList = [(111,'red'),(222,'pink'),(333,'green')] ``` Please notice the two lists are not one-to-one relationship. Some colors are not in `colorOrder`, and some colors in `colorOrder` never appear in `tupleList`. So It is different from other similiar duplicate problems. I need to Sort the tupleList according to the colorOrder. I can solve this problem using two nested for loops, but need a more efficient solution. ``` #First sort according to the color order for aColor in colorOrder: for aTuple in tupleList: if aTuple[1] == aColor: ResultList.append(aTuple) #Second add the tuples to the ResultList, whose color is not in the colorOrder for aTuple in tupleList: if aTuple[1] not in colorOrder: ResultList.append(aTuple) ```

Original source