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))
我假设有一个简单的列表函数可以做到这一点,但我无法找到它。
Given e.g.:
List(5, 2, 3, 3, 3, 5, 5, 3, 3, 2, 2, 2)
I'd like to get to:
List(List(5), List(2), List(3, 3, 3), List(5, 5), List(3, 3), List(2, 2, 2))
I would assume there is a simple List function that does this, but am unable to find it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
这是我通常使用的技巧:
实际上......事实并非如此,我通常对集合类型进行抽象并使用尾递归进行优化,但希望保持答案简单。
This is the trick that I normally use:
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.
这是另一种方法。
Here's another way.
该死的雷克斯克尔,写出了我想要的答案。由于存在细微的风格差异,因此我的看法是:
由于元素相同,因此我没有费心反转子列表。
Damn Rex Kerr, for writing the answer I'd go for. Since there are minor stylistic differences, here's my take:
Since the elements are identical, I didn't bother reversing the sublists.
或
[编辑]
Or
[Edit]
我在处理集合方法时拥有这些实现。最后,我检查了 inits 和 tails 的更简单实现,并忽略了 cluster。每一种新方法,无论多么简单,最终都会征收巨额税收,而这从外部很难看到。但这是我没有使用的实现。
[编辑:我忘记了其他人不会知道内部结构。该代码是从 TraversableLike 内部编写的,因此它不会开箱即用。]
I have these implementations lying around from working on collections methods. In the end I checked in simpler implementations of inits and tails and left out cluster. Every new method no matter how simple ends up collecting a big tax which is hard to see from the outside. But here's the implementation I didn't use.
[Edit: I forget other people won't know the internals. This code is written from inside of TraversableLike, so it wouldn't run out of the box.]
这是一个稍微干净一点的版本:
尾递归版本
Here's a slightly cleaner one:
tail-recursive version
这是受 @Kevin Wright 和 @Landei 启发的尾递归解决方案:
Here's a tail-recursive solution inspired by @Kevin Wright and @Landei:
这可能更简单:
this could be simpler: