Scala Split Seq 或 List by Delimiter [英] Scala Split Seq or List by Delimiter
本文介绍了Scala Split Seq 或 List by Delimiter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个这样的整数序列:
Let's say I have a sequence of ints like this:
val mySeq = Seq(0, 1, 2, 1, 0, -1, 0, 1, 2, 3, 2)
我想将其拆分为 0 作为分隔符,如下所示:
I want to split this by let's say 0 as a delimiter to look like this:
val mySplitSeq = Seq(Seq(0, 1, 2, 1), Seq(0, -1), Seq(0, 1, 2, 3, 2))
在 Scala 中执行此操作最优雅的方法是什么?
What is the most elegant way to do this in Scala?
推荐答案
这个没问题
mySeq.foldLeft(Vector.empty[Vector[Int]]) {
case (acc, i) if acc.isEmpty => Vector(Vector(i))
case (acc, 0) => acc :+ Vector(0)
case (acc, i) => acc.init :+ (acc.last :+ i)
}
其中 0(或其他)是您的分隔符.
where 0 (or whatever) is your delimiter.
这篇关于Scala Split Seq 或 List by Delimiter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文