按F#中的元组分组 [英] Group by with tuples in F#

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

问题描述

假设我有一个这样的tupples列表:

Suppose I have a list of tupples like these :

[("A",12); ("A",10); ("B",1);  ("C",2); ("C",1)]

我想做某种groupby我该如何处理?

And I would like to do some kind of groupby how do I handle that?

在伪代码SQL中,它看起来应该像这样:

In pseudocode-SQL it should look something like this :

SELECT fst(tpl), sum(lst(tpl)) FROM [TupplesInList] GROUP BY fst(tpl)

屈服

 [("A",22); ("B",1); ("C",3)]

如果键存在,我可以制作一个Dictionary并添加整数,但是我很难相信这将是像F#这样具有表现力的语言的最佳解决方案.

I could make a Dictionary and add the ints if the key exist, but I can hardly believe that would be the best solution in a language as expressive as F#.

推荐答案

一种解决方案:

let tuples = [("A",12); ("A",10); ("B",1);  ("C",2); ("C",1)]
tuples 
|> Seq.groupBy fst 
|> Seq.map (fun (key, values) -> (key, values |> Seq.sumBy snd))

...或不使用管道:

...or without piping:

let tuples = [("A",12); ("A",10); ("B",1);  ("C",2); ("C",1)]
Seq.map (fun (key, group) -> key, Seq.sumBy snd group)
        (Seq.groupBy fst tuples)

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

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