Scala Split Seq or 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) 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)) What is the most elegant way to do this in Scala? 回答1: This works alright 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) } where 0 (or whatever) is your delimiter. 回答2: Efficient O(n)