F#相当于toLookup

时间:2009-09-24 12:16:22

标签: f# lookup

鉴于此:

[
    ("A","A122");
    ("A","A123");
    ("B","B122");
    ("B","B123");
    ("C","C122");
]

是否有标准功能来实现这一目标?

[
    ("A",["A122";"A123"]);
    ("B",["B122";"B123"]);
    ("C",["C122"])
]

我想到了Seq.distinctBy,List.partition,Set,Map,但它们似乎都不是我想要的。

谢谢...在我等待的时候,我会尝试自己动手:)

2 个答案:

答案 0 :(得分:7)

傻了我,我没注意到Seq.groupBy!

[
    ("A","A122");
    ("A","A123");
    ("B","B122");
    ("B","B123");
    ("C","C122");
]
 |> Seq.groupBy (fun (a, b) -> a)
 |> Seq.map (fun (a, b) -> (a, Seq.map snd b))

输出:

seq
[("A", seq ["A122"; "A123"]); ("B", seq ["B122"; "B123"]);
 ("C", seq ["C122"])]

答案 1 :(得分:1)

对于O(1)查找:

[
    ("A","A122");
    ("A","A123");
    ("B","B122");
    ("B","B123");
    ("C","C122");
]
|> Seq.groupBy fst
|> dict