Scala:使用固定窗口计算列表的移动总和

Fly*_*con 7 scala sum list rolling-sum

我是 Scala 的新手,我想用列表的固定窗口计算移动总和。

例如:给定列表值 (1.0, 2.0, 3.0, 6.0, 7.0, 8.0, 12.0, 9.0, 4.0, 1.0) 和句点 4,函数应该返回: (1.0, 3.0, 6.0, 12.0, 18.0, 24.0, 33.0, 36.0, 33.0, 26.0)

如果 list.size < period 则只返回累积总和。

我做了一些尝试

def mavg(values: List[Double], period: Int): List[Double] = {
  if (values.size <= period) (values.sum ) :: List.fill(period -1)(values.sum ) else {
      val rest: List[Double] = mavg(values.tail, period)
      (rest.head + ((values.head - values(period)))):: rest
  }
}
Run Code Online (Sandbox Code Playgroud)

然而,我得到了

List(12.0, 18.0, 24.0, 33.0, 36.0, 33.0, 26.0, 26.0, 26.0, 26.0
Run Code Online (Sandbox Code Playgroud)

这是不正确的。我不想使用 Pyspark 来获得结果。有人可以帮忙吗?

非常感谢。

Use*_*123 5

  def mavg(values: Seq[Double], period: Int): Seq[Double] = {
    (Seq.fill(math.min(period - 1, values.length))(0.0) ++ values) // padding zeros
      .sliding(period)                  
      .map(_.sum)
      .toSeq
  }
Run Code Online (Sandbox Code Playgroud)

  • 请注意,当“values = Seq()”且“period &gt; 1”时,这会返回“List(0.0)” (2认同)

jwv*_*wvh 3

这是解决这个问题的一种方法。

def mavg(values: List[Double], period: Int): List[Double] =
  values.inits    //shrinking list of inits
        .toList   //result type
        .reverse  //growing list of inits
        .tail     //drop the empty one
        .map(_.takeRight(period).sum) //sum the window
Run Code Online (Sandbox Code Playgroud)

测试:

mavg(List(1.0, 2.0, 3.0, 6.0, 7.0, 8.0, 12.0, 9.0, 4.0, 1.0), 4)
//res0: List[Double] = List(1.0, 3.0, 6.0, 12.0, 18.0, 24.0, 33.0, 36.0, 33.0, 26.0)
Run Code Online (Sandbox Code Playgroud)