2017-01-24 31 views

回答

2

你可以试试这个方法,找出最长列表的长度,然后收集要素同时通过循环指数每个子列表:

val maxLength = a.map(_.length).max 
// maxLength: Int = 3 

(0 until maxLength) map (i => a flatMap (List(i) collect _)) 
// res45: scala.collection.immutable.IndexedSeq[List[Int]] = 
//  Vector(List(1, 4, 7), List(2, 5, 8), List(3, 6)) 
2

应该使用GROUPBY法列表中的组元素。在你的例子中,你正在分组每三个元素。在我的解决方案,我现在用的是模运算符组的每个第三个元素的列表:

val a = (1 to 8).toList.groupBy(_ % 3).values.toList 
a: List[List[Int]] = List(List(2, 5, 8), List(1, 4, 7), List(3, 6)) 

如果要排序的结果(如在你的例子),然后在结尾处添加sortBy():

val a = (1 to 8).toList.groupBy(_ % 3).values.toList.sortBy(_(0)) 
a: List[List[Int]] = List(List(1, 4, 7), List(2, 5, 8), List(3, 6))