【发布时间】:2015-02-19 08:29:17
【问题描述】:
我有两个列表,第一个列表是键顺序,第二个列表是元组列表。
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)
【问题讨论】:
-
当你写到你需要对“
tupleList根据@987654327@”进行排序时,你的意思是如果它的对应字符串在colorOrder中更早,则tupleList条目应该排在第一位吗?例如。对您给出的示例进行排序应该产生[(111,'red'),(333,'green'),(222,'pink')]? -
@FrerichRaabe 是的,你没看错。