问题
I have a list of tuples which i want to group by one of its elements as a key. For example, if i had this list of tuples:
[(A, "hello"), (A, "stack"), (A,"over"), (A, "flow"), (B, "how"), (B, "you"), (C, "doin")]
I would like to get a result in the form:
[(A, ["hello", "stack", "over", "flow"]), (B, ["how", "you"]), (C, ["doin"])]
I am new to F# so I am all out of ideas on how to do this. I thank you in advance.
cheers
回答1:
I think you are using incorrect delimiter for list elements - instead of ,
you need to use ;
.
To get results use this snippet:
[("A", "hello"); ("A", "stack"); ("A","over"); ("A", "flow"); ("B", "how"); ("B", "you"); ("C", "doin")]
|> Seq.groupBy fst
|> Seq.map (fun (key,groupping) -> key, (groupping |> Seq.map snd |> Seq.toList))
|> Seq.toList
来源:https://stackoverflow.com/questions/25395075/f-reduce-a-list-of-tuples-by-grouping-one-of-the-elements-into-arrays