【问题标题】:Manipulating an Fsharp list操作 Fsharp 列表
【发布时间】:2013-02-09 06:56:04
【问题描述】:

好吧,最近几天我一直在玩 F#,发现一些教程在网上流传(没有解决方案!)如果我有以下列表 -

let new = [
 (1808,"RS");
 (1974,"UE");
 (1066,"UE");
 (3005,"RS");
 (2007,"UE");
 (2012,"UE");
 ]

如何过滤此列表以首先显示组 RS 中的项目数,然后显示 UE? 我在想 List.filter,List.length,不太确定从这两个中去哪里来获得每个组的特定数字。感谢您的帮助

【问题讨论】:

    标签: list filter f# variable-length


    【解决方案1】:

    一般情况下,Seq.groupBy 可以轻松处理分组操作。

    如果您只想计算每个组中的项目数,Seq.countBy 是要走的路。

    [ (1808,"RS");
      (1974,"UE");
      (1066,"UE");
      (3005,"RS");
      (2007,"UE");
      (2012,"UE"); ]
    // 'countBy' returns a sequence of pairs denoting unique keys and their numbers of occurrences
    // 'snd' means that we try to pick a key as the *second* element in each tuple
    |> Seq.countBy snd
    // convert results back to an F# list
    |> Seq.toList
    
    // val it : (string * int) list = [("RS", 2); ("UE", 4)]
    

    【讨论】:

    • 你能向我解释一下 Seq.count By snd 和 Seq.toList 的基本含义吗?
    • 我在代码片段中添加了 cmets。您可以按照我的回答中的链接来了解这些操作。
    • 有没有办法通过 List.filter 和 list.length 来做同样的操作?
    猜你喜欢
    • 1970-01-01
    • 2019-04-10
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-09-03
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多