這個問題可能會被重複,但是,我還沒有遇到任何問題可以解決我的問題。如何獲得scala中選項列表的當前和下一個元素
所以我有一個List[ List[ Option[ Double ] ] ]
數據如下:
var tests = List(
List(Some(313.062468), Some(27.847252)),
List(Some(301.873641), Some(42.884065)),
List(Some(332.373186), Some(53.509768))
)
我想計算這個公式:以下
def findDifference(oldPrice: Option[Double], newPrice: Option[Double]): Option[Double] = {
return Some((newPrice.get - oldPrice.get)/oldPrice.get)
}
:
這是對兩個列表的元素進行計算:
(Some(301.062468) - Some(313.062468))/Some(313.062468)
(Some(332.373186) - Some(301.873641))/Some(301.873641)
(Some(42.884065) - Some(27.847252))/Some(27.847252)
(Some(53.509768) - Some(42.884065))/Some(42.884065)
結果應該返回: #
List(
List(Some(-0.03573991820699504), Some(0.5399747522663995))
List(Some(0.10103414428290529), Some(0.24777742035415723))
)
到目前爲止我的代碼
def findDifference(oldPrice: Option[Double], newPrice: Option[Double]): Option[Double] = {
return Some((newPrice.get - oldPrice.get)/oldPrice.get)
}
def get_deltas(data: List[List[Option[Double]]]): List[List[Option[Double]]] = {
for {
i <- data
// So this is where I am stuck. I have the current element i, but I need the same index element in the next list
} (findDifference(i,?) }
我如果輸出打印我的我在-理解
List(Some(313.062468), Some(27.847252))
List(Some(301.873641), Some(42.884065))
List(Some(332.373186), Some(53.509768))
我在哪裏停留?
我被困在事實上,我不知道如何從列表2和列表3中獲得列表1中的相同索引的元素,並進行必要的計算?
請幫我實現我的結果輸出
當您在'findDifference'方法中使用'.get'打開每個可能的值時,用'Some'包裝你的值有什麼意義? –
1 - 如果元素的索引很重要,則不能以這種方式使用'for'理解。 2 - 如果其中任何選項爲「無」,您的代碼將拋出運行時異常。 (這是選項的用途。)3 - 我認爲你的數據表示太複雜了。 – jwvh
我添加了一些解釋我的問題。它不需要在裏面。我只是不知道該怎麼做計算。有沒有辦法呢? @jwvh –