F# Filtering multiple years

老子叫甜甜 提交于 2020-01-06 03:06:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!