Scala集合基础:sliding方法介绍

分享 未结
0 2 0 14
小编 2017-08-15发布
收藏 点赞

sliding方法定义在IterableLike Trait中,用于将列表分割成固定大小的子列表,该方法的API文档如下:

/** Groups elements in fixed size blocks by passing a "sliding window"
 *  over them (as opposed to partitioning them, as is done in grouped.)
 *  @see [[scala.collection.Iterator]], method `sliding`
 *
 *  @param size the number of elements per group
 *  @param step the distance between the first elements of successive
 *         groups
 *  @return An iterator producing ${coll}s of size `size`, except the
 *          last and the only element will be truncated if there are
 *          fewer elements than size.
 */
def sliding(size: Int, step: Int): Iterator[Repr]

正如sliding字面上所表达的含义"滑行,移动",sliding方法使用一个滑动窗口在列表上进行滑动,size参数设置窗口大小,step参数设置每次滑动需要滑过的元素个数,step参数默认为1。我们使用sliding方法可以很容易将列表元素两两分组:

val list = ('a' to 'e').map(_.toString)
list.sliding(2).toList //输出:List(Vector(a, b), Vector(b, c), Vector(c, d), Vector(d, e))

如果size参数和step参数相等,则可以实现将列表分割成固定大小的子列表:

list.sliding(2, 2).toList //输出:List(Vector(a, b), Vector(c, d), Vector(e))

如果step参数大于size参数,就是数据采样了,日常开发中应该很少用到。

回帖
  • 消灭零回复