gpt4 book ai didi

scala - 在 Scala 中如何用反向维度对列表中的元素进行分组?

转载 作者:行者123 更新时间:2023-12-02 08:15:57 24 4
gpt4 key购买 nike

给定:

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))

最佳答案

你可以试试这个方法,找出最长的List的长度,然后在遍历索引的同时从每个子列表中收集元素:

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))

关于scala - 在 Scala 中如何用反向维度对列表中的元素进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41818840/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com