简体   繁体   English

Python根据另一个列表排序一个列表

[英]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 . 有些颜色不是colorOrder ,对于某些颜色colorOrder不会出现在tupleList So It is different from other similiar duplicate problems. 所以它与其他类似的重复问题不同。

I need to Sort the tupleList according to the colorOrder. 我需要根据colorOrder对tupleList进行排序。

I can solve this problem using two nested for loops, but need a more efficient solution. 我可以使用两个嵌套for循环来解决这个问题,但需要一个更有效的解决方案。

#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: 首先,我将colorOrder映射:

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

Now sorting becomes a bit easier with colorMap.get 现在使用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])]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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