Scala List 函数,用于对连续的相同元素进行分组 [英] Scala List function for grouping consecutive identical elements
本文介绍了Scala List 函数,用于对连续的相同元素进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定例如:
List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)
我想去:
List(List(5), List(2), List(3, 3, 3), List(5, 5), List(3, 3), List(2, 2, 2))
我认为有一个简单的 List 函数可以做到这一点,但我找不到它.
I would assume there is a simple List function that does this, but am unable to find it.
推荐答案
这是我通常使用的技巧:
This is the trick that I normally use:
def split[T](list: List[T]) : List[List[T]] = list match {
case Nil => Nil
case h::t => val segment = list takeWhile {h ==}
segment :: split(list drop segment.length)
}
实际上......不是,我通常对集合类型进行抽象并使用尾递归进行优化,但希望保持简单的答案.
Actually... It's not, I usually abstract over the collection type and optimize with tail recursion as well, but wanted to keep the answer simple.
这篇关于Scala List 函数,用于对连续的相同元素进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文