按类别交替条件按降序对元组列表进行排序

时间:2016-02-24 18:43:51

标签: scala sorting

给出一个元组列表:

val mylist = List(('orange', 0.9, 1), ('apple', 0.8, 1), ('mellon', 0.7, 1), 
                  ('car', 0.5, 2), ('truck', 0.5, 2),
                  ('tablet', 0.3, 3))

我想按照元组的第二个元素的降序对它们进行排序。但是,我想按类别选择它们,一次一个(第三个元素)。输出应该是以下列表:

('orange', 0.9, 1)
('car', 0.5, 2)
('tablet', 0.3, 3)
('apple', 0.8, 1) 
('truck', 0.5, 2)
('mellon', 0.7, 1) 

在Scala中执行此操作的功能方法是什么?

1 个答案:

答案 0 :(得分:3)

尝试:

mylist.groupBy(_._3) // group by category
      .toList
      .sortBy(_._1)  // sort by asc category
      .map(_._2.sortBy(-_._2)) // drop the category key + sort each group by desc rank
      .flatMap(_.zipWithIndex) 
      .sortBy(_._2) // sort by index (stable sort)
      .map(_._1)    // drop the index

> res: List[(String, Double, Int)] = List((orange,0.9,1), (car,0.5,2), (tablet,0.3,3), (apple,0.8,1), (truck,0.5,2), (mellon,0.7,1))