【问题标题】:Python Sort One List According to Another ListPython根据另一个列表对一个列表进行排序
【发布时间】: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 是的,你没看错。

标签: python list sorting


【解决方案1】:

首先,我要为colorOrder 做一个映射:

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

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

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

这会将不在地图中的东西放在首位。如果您希望添加它们last,只需使用一个非常大的数字:

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

【讨论】:

  • 实际上,首先我会将所有namesLikeThis 更改为names_like_this,因为这是更典型的python 命名约定;-)。 然后我会进行映射...
  • float('inf') 可以替换为len(colorOrder)?
  • @JamesKing -- 当然,如果你喜欢 :-) 它真的不会以某种方式产生影响。我更喜欢无穷大,因为当我看到它时,我立即知道它会在列表的末尾。我看到len(something) 然后我必须开始思考......
【解决方案2】:

检查此解决方案:

     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])]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-15
    • 1970-01-01
    • 2013-09-12
    • 1970-01-01
    • 2023-04-01
    • 2021-05-02
    • 2011-03-22
    相关资源
    最近更新 更多