假设我有一个像这样的tupples列表:
[("A",12); ("A",10); ("B",1); ("C",2); ("C",1)]
我想做某种groupby
我该如何处理?
在伪代码SQL中,它看起来像这样:
SELECT fst(tpl), sum(lst(tpl)) FROM [TupplesInList] GROUP BY fst(tpl)
屈服
[("A",22); ("B",1); ("C",3)]
如果密钥存在,我可以创建一个字典并添加整数,但我几乎无法相信这将是F#表达的最佳解决方案。
答案 0 :(得分:27)
一个解决方案:
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))
编辑 ...或没有管道:
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)
答案 1 :(得分:16)
为了扩展Johan的答案,我倾向于做很多这样的事情,所以做了以下广义的功能。
let group_fold key value fold acc seq =
seq |> Seq.groupBy key
|> Seq.map (fun (key, seq) -> (key, seq |> Seq.map value |> Seq.fold fold acc))
适用于您的元组案例,如下所示
let tuples = [("A",12); ("A",10); ("B",1); ("C",2); ("C",1)]
let regular = group_fold fst snd (+) 0 tuples
let piped = tuples |> group_fold fst snd (+) 0
但也可以使用其他序列,如字符串列表
let strings = ["A12"; "A10"; "B1"; "C2"; "C1"]
let regular = group_fold (fun (x : string) -> x.[0]) (fun (x : string) -> int x.[1..]) (+) 0 strings
let piped = strings |> group_fold (fun x -> x.[0]) (fun x -> int x.[1..]) (+) 0