假设我需要将给定列表拆分为3个段,如下所示:
val l = (0 until 5).toList
val segments = l.tails.map(_.take(3)).filter(_.size == 3).toList
segments: List[List[Int]] = List(List(0, 1, 2), List(1, 2, 3), List(2, 3, 4))
我得到了我需要的segments
,但代码显然很难看。你会怎么改写它?
答案 0 :(得分:6)
使用sliding
:
val segments: Iterator[List[Int]] = l.sliding(3)
segments.toList
> List[List[Int]] = List(List(0, 1, 2), List(1, 2, 3), List(2, 3, 4))