Python根据另一个列表对一个列表进行排序
我有两个列表,第一个列表是键顺序,第二个列表是元组列表Python根据另一个列表对一个列表进行排序,python,list,sorting,Python,List,Sorting,我有两个列表,第一个列表是键顺序,第二个列表是元组列表 colorOrder = ['red', 'blue', 'yellow', 'green'] tupleList = [(111,'red'),(222,'pink'),(333,'green')] 请注意,这两个列表不是一对一的关系。有些颜色不在colorOrder中,而colorOrder中的一些颜色从不出现在tupleList中。因此,它不同于其他类似的重复问题 我需要根据颜色顺序对元组列表进行排序 我可以使用两个嵌套for循环来
colorOrder = ['red', 'blue', 'yellow', 'green']
tupleList = [(111,'red'),(222,'pink'),(333,'green')]
请注意,这两个列表不是一对一的关系。有些颜色不在colorOrder
中,而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进行排序变得更加容易。获取
sorted(tupleList, key=lambda tup: colorMap.get(tup[1], -1))
这就把不在地图上的东西放在第一位。如果您想最后添加,只需使用一个非常大的数字:
sorted(tupleList, key=lambda tup: colorMap.get(tup[1], float('inf')))
检查此解决方案:
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])]
当您编写需要根据colorOrder
对tupleList
进行排序时,您的意思是如果tupleList条目的相应字符串在colorOrder
中出现较早,则该条目应排在第一位吗?例如,对您给出的示例进行排序应该会产生[(111,'red'),(333,'green'),(222,'pink')]
?@FrerichRaabe是的,您理解得对。实际上,首先我会将所有名称(如this
)更改为名称(如this
,因为这是python更典型的命名约定;-)。然后我会做映射,float('inf')
可以被len(colorOrder)
?@JamesKing替换——当然,如果你喜欢的话:-)它真的没有任何区别。我更喜欢无穷大,因为当我看到它时,我马上知道它会在列表的末尾。我看到一个len(某物)
,然后我不得不开始思考。。。