![](/img/trans.png)
[英]How to group by elements of tuple in Scala and map to list of new elements?
[英]In Scala how to group elements in list with reverse dimension?
鉴于:
scala> val a = (1 to 8).toList.grouped(3).toList
a: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8))
如何扭转在维和族元素a
以这种方式:
List(List(1, 4, 7), List(2, 5, 8), List(3, 6))
您可以尝试此方法,找出最长列表的长度,然后在循环遍历索引时从每个子列表中收集元素:
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))
也许你想调换的方法,但官方transpoes方法不支持长度不等的子列表。 也许您想尝试:
应该使用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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.