F# 相当于 toLookup

发布于 2024-08-05 11:14:35 字数 353 浏览 4 评论 0原文

鉴于此:

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

是否有标准函数可以实现此目的?

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

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

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

Given this:

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

Is there a standard function to get this?

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

I thought of Seq.distinctBy, List.partition, Set, Map, but none of them seem to be what I'm looking for.

Thanks... while I'm waiting, I'll try to roll my own :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梦与时光遇 2024-08-12 11:14:35

愚蠢的我,我没有注意到 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"])]

Silly me, I didn't notice 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))

Output :

seq
[("A", seq ["A122"; "A123"]); ("B", seq ["B122"; "B123"]);
 ("C", seq ["C122"])]
居里长安 2024-08-12 11:14:35

对于 O(1) 查找:

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

For O(1) lookup:

[
    ("A","A122");
    ("A","A123");
    ("B","B122");
    ("B","B123");
    ("C","C122");
]
|> Seq.groupBy fst
|> dict
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文