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')]
请注意,这两个列表不是一对一的关系. colorOrder
中没有某些颜色,colorOrder
中的某些颜色从未出现在tupleList
中.因此,它不同于其他类似的重复问题.
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.
我需要根据colorOrder对tupleList进行排序.
I need to Sort the tupleList according to the colorOrder.
我可以使用两个嵌套的for循环来解决此问题,但需要更有效的解决方案.
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)
推荐答案
首先,我将colorOrder
映射为:
colorMap = {c: i for i, c in enumerate(colorOrder)}
现在,使用colorMap.get
sorted(tupleList, key=lambda tup: colorMap.get(tup[1], -1))
这会将事物不在地图中首先.如果您希望将它们添加为 last ,只需使用一个非常大的数字即可:
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')))
这篇关于Python根据另一个列表对一个列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!