【问题标题】:How to sort a List of Lists of pairs of number in descending order by the second item in each pair in Scala?如何按Scala中每对中的第二项按降序对数对列表的列表进行排序?
【发布时间】:2016-10-18 13:29:08
【问题描述】:

我有一个类似List(List(0, 2), List(0, 3), List(2, 3), List(3, 2), List(3, 0), List(2, 0))) 的列表,请注意此列表将只包含对,不会包含重复的对。我想按此较大列表中每个子列表中的第二项按降序对列表进行排序。如果有重复的值,我真的不知道哪个先出现。

对于这种情况,答案可能类似于 List(List(0,3), List(2,3), List(0,2), List(3,2), List(3,0), List(2,0))

我的想法是遍历更大的列表并获取一个包含每对中的每个第二个项目的列表并对它们进行排序,但是我无法跟踪每对中的第二个项目属于哪个对。也许有更聪明的方法?

【问题讨论】:

    标签: list scala sorting


    【解决方案1】:

    一个简单的解决方案是:

    list.sortBy(-_.last)
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      list.sortBy(-_(1))
      

      【讨论】:

        【解决方案3】:

        如果列表总是长度为 2,我会使用元组而不是列表。然后就是用sortBy

        scala> val l1 = List(List(0, 2), List(0, 3), List(2, 3), List(3, 2), List(3, 0), List(2, 0))
        l1: List[List[Int]] = List(List(0, 2), List(0, 3), List(2, 3), List(3, 2), List(3, 0), List(2, 0))
        
        scala> val l2 = l1.map(x => (x(0), x(1)))
        l2: List[(Int, Int)] = List((0,2), (0,3), (2,3), (3,2), (3,0), (2,0))
        
        scala> l2.sortBy(-_._2)
        res1: List[(Int, Int)] = List((0,3), (2,3), (0,2), (3,2), (3,0), (2,0))
        

        【讨论】:

          【解决方案4】:

          list.sortBy( sublist => -1 * sublist.tail.head )

          【讨论】:

          • 正如其他答案所示,您可以在此处使用_ 语法
          猜你喜欢
          • 2022-01-15
          • 1970-01-01
          • 2022-01-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-13
          • 2015-10-19
          • 2020-05-18
          相关资源
          最近更新 更多