F#筛选多年 [英] F# Filtering multiple years

查看:146
本文介绍了F#筛选多年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是找到随后几年的太阳总量 - 1960,1970,1980,1990,2000,2010。数据来自txt文件,并且年,月,maxt,mint,afday,rain和sun已经被定义,并从元组中取出相关元素,然后忽略其余元素。

  //示例
let sun(_,_,_,_,_,_,t)= t

我找到了1960年的太阳总量。但是,我不确定如何找到剩余的年份。

  let Q6 = 
ds |> List.filter(fun s-> year(s)= 1960)
|> List.sumBy sun

上面的方法是一个布尔值,所以不会工作多年,什么是最好的方法?
我相信答案应该是这样的:

  val Q6:float list = [1434.4; 1441.8; 1393.0; 1653.0; 1599.5; 1510.2] 


解决方案



  let Q6 = 
let years = [1960; 1970; 1980; 1990; 2000; 2010]
//或让年= [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值)
|> Seq.toList

在这里您将看到如下所示的内容:

  val Q6:(int * float)list = [(1960,1434.4); (1980,1441.8)] 

如果你不想在结果中有年份,从lambda中删除 year,


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]

解决方案

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.

这篇关于F#筛选多年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆