Scala:滑动(N,N)与分组(N) [英] Scala: sliding(N,N) vs grouped(N)
问题描述
我最近发现自己使用了 slide(n,n),当我需要以 n 个元素为一组迭代集合而不重新处理其中任何一个时.我想知道使用 grouped(n) 迭代这些集合是否更正确.我的问题是,就性能而言,是否有特殊原因在这种特定情况下使用一种或另一种.
I found myself lately using sliding(n,n) when I need to iterate collections in groups of n elements without re-processing any of them. I was wondering if it would be more correct to iterate those collections by using grouped(n). My question is if there is an special reason to use one or another for this specific case in terms of performance.
val listToGroup = List(1,2,3,4,5,6,7,8)
listToGroup: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)
listToGroup.sliding(3,3).toList
res0: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8))
listToGroup.grouped(3).toList
res1: List[List[Int]] = List(List(1, 2, 3), List(4, 5, 6), List(7, 8))
推荐答案
使用 sliding
而不是 grouped
的原因真的只适用于你想要'windows' 的长度与您滑动"的长度不同(也就是说,使用 sliding(m, n)
where m != n
):>
The reason to use sliding
instead of grouped
is really only applicable when you want to have the 'windows' be of a length different than what you 'slide' by (that is to say, using sliding(m, n)
where m != n
):
listToGroup.sliding(2,3).toList
//returns List(List(1, 2), List(4, 5), List(7, 8))
listToGroup.sliding(4,3).toList
//returns List(List(1, 2, 3, 4), List(4, 5, 6, 7), List(7, 8))
正如 som-snytt 在评论中指出的那样,不会有任何性能差异,因为它们都是在 Iterator
中实现的,返回一个新的 GroupedIterator
.但是,编写 grouped(n)
比编写 sliding(n, n)
更简单,并且您的代码在其预期行为中会更清晰、更明显,因此我建议grouped(n)
.
As som-snytt points out in a comment, there's not going to be any performance difference, as both of them are implemented within Iterator
as returning a new GroupedIterator
. However, it's simpler to write grouped(n)
than sliding(n, n)
, and your code will be cleaner and more obvious in its intended behavior, so I would recommend grouped(n)
.
作为使用 sliding
的示例,请考虑这个问题,其中 grouped
根本不够用:
As an example for where to use sliding
, consider this problem where grouped
simply doesn't suffice:
给定一个数字列表,找出和最大长度为 4 的子列表.
Given a list of numbers, find the sublist of length 4 with the greatest sum.
现在,抛开动态规划方法可以产生更有效的结果这一事实,这可以解决为:
Now, putting aside the fact that a dynamic programming approach can produce a more efficient result, this can be solved as:
def maxLengthFourSublist(list: List[Int]): List[Int] = {
list.sliding(4,1).maxBy(_.sum)
}
如果你在这里使用grouped
,你不会得到所有的子列表,所以sliding
更合适.
If you were to use grouped
here, you wouldn't get all the sublists, so sliding
is more appropriate.
这篇关于Scala:滑动(N,N)与分组(N)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!