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

How to add List of Option of doubles in 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))
)

我想对每个嵌套列表的所有值求和。

我的以下代码不起作用:

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

展平、收集和求和

展平、收集和求和

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