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

Jam*_*ing 3 python sorting list

我有两个列表,第一个列表是键顺序,第二个列表是元组列表.

colorOrder = ['red', 'blue', 'yellow', 'green']
tupleList = [(111,'red'),(222,'pink'),(333,'green')]
Run Code Online (Sandbox Code Playgroud)

请注意这两个列表不是一对一的关系.有些颜色不在colorOrder,有些颜色colorOrder从未出现过tupleList.所以它与其他类似的重复问题不同.

我需要根据colorOrder对tupleList进行排序.

我可以使用两个嵌套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)
Run Code Online (Sandbox Code Playgroud)

mgi*_*son 5

首先,我做colorOrder一个映射:

colorMap = {c: i for i, c in enumerate(colorOrder)}
Run Code Online (Sandbox Code Playgroud)

现在排序变得更容易了 colorMap.get

sorted(tupleList, key=lambda tup: colorMap.get(tup[1], -1))
Run Code Online (Sandbox Code Playgroud)

这使得事情无法在地图第一.如果您最后添加它们,只需使用一个非常大的数字:

sorted(tupleList, key=lambda tup: colorMap.get(tup[1], float('inf')))
Run Code Online (Sandbox Code Playgroud)

  • 实际上,首先我会将所有`namesLikeThis`更改为`names_like_this`,因为这是python的更典型的命名约定;-)._Then_我会做出映射...... (3认同)