如何在scala中添加双精度选项列表

时间:2016-11-18 10:34:46

标签: scala list nested-lists scala-option

我有一个像这样的选项列表,

var data = List(
  List(Some(313.062468), Some(27.847252)),
  List(Some(301.873641), Some(42.884065)),
  List(Some(332.373186), Some(53.509768))
)

我想总结每个嵌套列表的所有值。

我有以下代码不起作用:

return data.flatten.foldLeft((Some(0), Some(0))) {
  case ((accA, accB), (a, b)) => {
    (_ + a, _ + b)
  }
}

1 个答案:

答案 0 :(得分:2)

展平,收集和汇总

展平,收集和总结

data.flatten.collect { case Some(value) => value }.sum

Scala REPL

scala> var data = List(
     |   List(Some(313.062468), Some(27.847252)),
     |   List(Some(301.873641), Some(42.884065)),
     |   List(Some(332.373186), Some(53.509768))
     | )
data: List[List[Some[Double]]] = List(List(Some(313.062468), Some(27.847252)), List(Some(301.873641), Some(42.884065)), List(Some(332.373186), Some(53.509768)))

scala>

scala> data.flatten
res2: List[Some[Double]] = List(Some(313.062468), Some(27.847252), Some(301.873641), Some(42.884065), Some(332.373186), Some(53.509768))

scala> data.flatten.collect { case Some(value) => value }.sum
res3: Double = 1071.55038

选项是可迭代的

看起来很整洁。

data.iterator.flatMap(_.iterator.flatMap(_.iterator)).sum

Scala REPL

scala> data.iterator.flatMap(_.iterator.flatMap(_.iterator)).sum
res5: Double = 1071.55038

为了理解

(for {
  list <- data.iterator
  elem <- list.iterator
  value <- elem.iterator
  } yield value).sum