Iterable.sliding的输出为Tuple [英] Output of Iterable.sliding as Tuple

查看:120
本文介绍了Iterable.sliding的输出为Tuple的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对集合的滑动方法以X [Iterable [A]]的形式返回给定大小的滑动窗口,其中X是集合的类型,A是元素类型。通常我需要两个或三个元素,我更喜欢他们命名。滑动(2)的一个丑陋的解决方法如下:

The method sliding on collections returns a sliding window of given size in the form of X[Iterable[A]] with X being the type of the collection and A the element type. Often I need two or three elements and I prefer to have them named. One ugly workaround for sliding(2) is the following:

points.sliding(2).foreach{ twoPoints =>
      val (p1,p2) = (twoPoints.head,twoPoints.last)
      //do something
}

这吸引,只适用于两个元素。另请注意

This sucks and only works for two elements. Also note that

(a,b) = (twoPoints(0),twoPoints(1))

无法使用。帮助我!

推荐答案

我在这个答案。 / p>

I did a lot of that in this answer just last week.

points.sliding(2).foreach { case X(p1, p2) => ... }

如果 points Array ,然后用 Array 替换 X 。如果是 List ,用 List 替换 X

If points is an Array, then replace X with Array. If it is a List, replace X with List, and so on.

请注意,您正在进行模式匹配,因此您需要 {} 而不是()作为参数。

Note that you are doing a pattern match, so you need to {} instead of () for the parameter.

这篇关于Iterable.sliding的输出为Tuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆