给出了一个元组列表:
val mylist = List(('orange', 0.9, 10), ('apple', 0.8, 10), ('mellon', 0.7, 10),
('car', 0.5, 2), ('truck', 0.5, 2),('tablet', 0.3, 3))我想根据元组的第二个元素按降序排序。然而,我想按类别挑选它们,一次一次(第三要素)。输出应该是以下列表:
('orange', 0.9, 10)
('car', 0.5, 2)
('tablet', 0.3, 3)
('apple', 0.8, 10)
('truck', 0.5, 2)
('mellon', 0.7, 10) 在Scala中实现它的功能方式是什么?
PS:注意,结果必须反映第三个元素的顺序,即10出现在2之前,2出现在3之前。
发布于 2016-10-21 10:39:26
可以通过向列表中的每个项添加两个索引来做到这一点:
一旦添加了这些内容,就可以按两者进行排序(索引以类别为优先)。
// traverse once to get a map of Category -> CategoryIndex
val categoryOrder: Map[Int, Int] = mylist.map(_._3).distinct.zipWithIndex.toMap
val result: List[(String, Double, Int)] = mylist
.groupBy(_._3).mapValues(_.sortBy(-_._2).zipWithIndex) // add the index of each item within its category
.toList.flatMap(_._2) // remove group keys and flatMap to get back to tuples
.sortBy { case (t, indx) => (indx, categoryOrder(t._3)) } // order by index in category and category index
.map(_._1) // remove indices
println(result)
// List((orange,0.9,10), (car,0.5,2), (tablet,0.3,3), (apple,0.8,10), (truck,0.5,2), (mellon,0.7,10))https://stackoverflow.com/questions/40173020
复制相似问题