Python 根据另一个列表对一个列表进行排序

标签 python list sorting

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

colorOrder = ['red', 'blue', 'yellow', 'green']
tupleList = [(111,'red'),(222,'pink'),(333,'green')]

请注意这两个列表不是一对一的关系。 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)

最佳答案

首先,我将 colorOrder 设为一个映射:

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

现在使用 colorMap.get 排序变得更容易一些

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

这会将不在 map 中的东西放在第一位。如果您希望将它们添加到最后,只需使用一个非常大的数字:

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

关于Python 根据另一个列表对一个列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28601613/

相关文章:

list - Haskell:如何从一个公共(public)列表中创建文件列表和目录列表

python - 用 python 估计欧几里德变换

Python:3D 列表的索引错误

java - 我怎样才能访问这个列表并且也是线程安全的?

python - 如何在 Python 中读取输入文件?

python - 如何对排序文件进行分组并保留组顺序

java - 如何将数据作为参数从java传递到python脚本

python - 一个傅里叶如何变换 1's and 0' 的数组

python - 为 python 排序表 xlsxwriter

java - 在 3D Young Tableau 上调用 Maxify?