问题
My objective is to find the total amount of sun for the following years - 1960,1970,1980,1990,2000,2010. The data comes from a txt file and year, month, maxt, mint, afday, rain and sun have already been defined and take the relevant element from the tuple, then it ignores the rest.
// Example
let sun (_,_,_,_,_,_,t) = t
I have found the total amount of sun for the year 1960. However, I am not sure how to find the remaining years.
let Q6 =
ds |> List.filter (fun s-> year(s)=1960)
|> List.sumBy sun
The above method is a boolean so wouldn't work for multiple years, what is the best method? I believe the answer should be like this:
val Q6 : float list = [1434.4; 1441.8; 1393.0; 1653.0; 1599.5; 1510.2]
回答1:
You can group them before applying the sum:
let Q6 =
let years = [1960;1970;1980;1990;2000;2010]
// or let years = [1960 .. 10 .. 2010]
ds |> Seq.filter (fun value -> List.exists ((=) (year value)) years)
|> Seq.groupBy year
|> Seq.map (fun (year, values) -> year, Seq.sumBy sun values)
|> Seq.toList
Here you will get something like:
val Q6 : (int * float) list = [(1960, 1434.4); (1980, 1441.8)]
If you don't want to have the year in the results you can remove the year ,
from the lambda.
来源:https://stackoverflow.com/questions/28742791/f-filtering-multiple-years