好的,最近几天我一直在玩 F#,发现一些教程在网上流传(没有解决方案!)如果我有以下列表 -
let new = [
(1808,"RS");
(1974,"UE");
(1066,"UE");
(3005,"RS");
(2007,"UE");
(2012,"UE");
]
我将如何过滤此列表以首先显示 RS 组中的项目数,然后显示 UE?我在想 List.filter,List.length,不太确定从这两个中去哪里以获得每个组的特定数字。谢谢你的帮助
好的,最近几天我一直在玩 F#,发现一些教程在网上流传(没有解决方案!)如果我有以下列表 -
let new = [
(1808,"RS");
(1974,"UE");
(1066,"UE");
(3005,"RS");
(2007,"UE");
(2012,"UE");
]
我将如何过滤此列表以首先显示 RS 组中的项目数,然后显示 UE?我在想 List.filter,List.length,不太确定从这两个中去哪里以获得每个组的特定数字。谢谢你的帮助
一般来说,分组操作很容易由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)]