简体   繁体   中英

Python Sort One List According to Another List

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)

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')))

Check this Solution:

     xx = dict([(x[1],x[0]) for x in enumerate(colorOrder)])
     [x[1] for x in sorted([(xx.get(y[1],999),y) for y in tupleList])]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM