如何在for循环Scala中创建选项列表[Double]

How to create List of List of Option[Double] In for loop Scala

我很确定这个问题可能会被重复,但我还没有找到这个问题的答案。请原谅我对 Scala 的一知半解。我是新手。

我的目标是遍历两个列表(长度不同)和 return List[List[Option[Double]]].

到目前为止我的代码:

 def getDoubles(symbol: String, year: Int): Option[Double] = {
   return Some(140.0)
 }

 // this method loops over list of strings and range of time. returns list of list of Option[Double]
 def checkList(CSV: List[String], time: Range): List[List[Option[Double]]] = {
   // this variable is whats going to be returned at the end
   var listOfLists = List[List[Option[Double]]]()
     // So we are going to loop over our list and our time, and link each element in our list to all the elements in          our time range
   for {
     i < -CSV
     j < -time
       // the method getDoubles is pretty long, so i just made another version simplfying my question.
       // get doubles bascially returns Option of doubles
   }
   yield (listOfLists = getDoubles(j, i)::listOfLists)
   return listOfLists
 }

上面的代码,当我用更复杂的数据调用它时,它returns:

Vector(
  Some(313.062468), 
  Some(27.847252), 
  Some(301.873641), 
  Some(42.884065), 
  Some(332.373186), 
  Some(53.509768)
)

但我想 return 像这样:

List(
  List(Some(313.062468), Some(27.847252)),
  List(Some(301.873641), Some(42.884065)),
  List(Some(332.373186), Some(53.509768))
)

我该怎么做?

您不需要为此使用任何可变变量。首先,如果你需要一个嵌套列表,你需要一个嵌套for。然后在 yield 中,您应该写下此 for 生成的集合中每个元素的外观。它不是循环体,你不应该在那里做任何突变。整个 for-expression 是结果集合。查看 "How does yield work?".

上的 Scala 常见问题解答
def checkList(csv: List[String], time: Range): List[List[Option[Double]]] = {
  for {
    symbol <- csv
  } yield {
    for {
      year <- time.toList
    } yield getDoubles(symbol, year)
  }
}

For-comprehension 只是 mapflatMapfilter 组合的语法糖。在这种情况下,用 map 写起来更简洁明了:

def checkList(csv: List[String], time: Range): List[List[Option[Double]]] = {
  csv map { symbol =>
    time map { year =>
      getDoubles(symbol, year)
    }
  }
}

另见 "What is Scala's yield?" 问题。