将scala列表拆分为n个交错列表

Chr*_*s B 5 scala scala-collections

鉴于List如此

List(1, 2, 3, 4, 5, 6, 7)
Run Code Online (Sandbox Code Playgroud)

将它分成n个子列表的最佳方法是什么,将项目以循环方式放入每个列表?

例如,如果n = 3,结果应该是

List(List(1, 4, 7), List(2, 5), List(3, 6))
Run Code Online (Sandbox Code Playgroud)

我认为集合API中会有一个方法来执行此操作,但我似乎无法找到它.

优雅单行的奖励积分;)

sen*_*nia 10

scala> def round[T](l: List[T], n: Int) = (0 until n).map{ i => l.drop(i).sliding(1, n).flatten.toList }.toList
round: [T](l: List[T], n: Int)List[List[T]]

scala> round((1 to 7).toList, 3)
res4: List[List[Int]] = List(List(1, 4, 7), List(2, 5), List(3, 6))
Run Code Online (Sandbox Code Playgroud)


mis*_*tor 5

这是一个简单的单行:

scala> List.range(1, 10)
res11: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> res11.grouped(3).toList.transpose
res12: List[List[Int]] = List(List(1, 4, 7), List(2, 5, 8), List(3, 6, 9))
Run Code Online (Sandbox Code Playgroud)

不幸的是,当您的列表不可转置时,它就不起作用。

scala> List.range(1, 8).grouped(3).toList.transpose
java.lang.IllegalArgumentException: transpose requires all collections have the 
same size
Run Code Online (Sandbox Code Playgroud)

您可以使用以下方法使其可转置,然后应用上述方法。

scala> def extend[A](xs: List[A], c: Int): List[Option[A]] = {
     |   val n = Stream.iterate(c)(c +).find(_ >= xs.length).get
     |   xs.map(Some(_)).padTo(n, None)
     | }
extend: [A](xs: List[A], c: Int)List[Option[A]]

scala> List.range(1, 8)
res13: List[Int] = List(1, 2, 3, 4, 5, 6, 7)

scala> extend(res13, 3).grouped(3).toList.transpose.map(_.flatten)
res14: List[List[Int]] = List(List(1, 4, 7), List(2, 5), List(3, 6))
Run Code Online (Sandbox Code Playgroud)

放在一起:

scala> def round[A](xs: List[A], c: Int) = {
     |   val n = Stream.iterate(c)(c +).find(_ >= xs.length).get
     |   val ys = xs.map(Some(_)).padTo(n, None)
     |   ys.grouped(c).toList.transpose.map(_.flatten)
     | }
round: [A](xs: List[A], c: Int)List[List[A]]

scala> round(List.range(1, 10), 3)
res16: List[List[Int]] = List(List(1, 4, 7), List(2, 5, 8), List(3, 6, 9))

scala> round(List.range(1, 8), 3)
res17: List[List[Int]] = List(List(1, 4, 7), List(2, 5), List(3, 6))
Run Code Online (Sandbox Code Playgroud)