从 F# 中的序列中获取不同值的计数

Get the count of distinct values from a Sequence in F#

我在 F# 中有一系列国家/地区名称。我想知道我在序列中有多少个不同的国家/地区条目。

Microsoft docs and MSDN 中的 countBy 示例使用 ifelse 来获取密钥,但由于我有大约 240 个不同的条目,我想我不需要每个条目一个elif语句,对吧?

那么,是否可以选择使用另一个序列来获取 countBy 的键?

#load "packages/FsLab/FsLab.fsx"
open FSharp.Data
open System

type City = JsonProvider<"city.list.json",SampleIsList=true>

let cities = City.GetSamples()

let Countries = seq { for city in cities do yield city.Country.ToString() } |> Seq.sort

let DistinctCountries = Countries |> Seq.distinct

//Something like this
let Count = Seq.countBy DistinctCountries Countries

任何对我感兴趣的人city.list.json

更新

我的输入序列是这样的(有更多的条目)每个代码都重复,因为原始列表中有该国家/地区的许多城市:

{ "AR","AR","AR","MX","MX" }

结果我预计:

{("AR", 3),("MX", 2),...}

您可以将国家/地区分组,然后计算每组中的条目数:

let countsByCountry = 
  Countries 
  |> Seq.groupBy id 
  |> Seq.map (fun (c, cs) -> c, Seq.length cs)

这个组合也是作为一个函数实现的,countBy:

let countsByCountry = Countries |> Seq.countBy id
Countries |> Seq.countBy id

id是恒等函数fun x -> x。使用它是因为这里的 "key" 是序列项本身。

So, is there an option to use another sequence to get the keys for the countBy?

您不需要从某处获取 密钥,传递给Seq.countBy 的函数会生成密钥。你应该能够摆脱这个:

let count = 
    cities
    |> Seq.countBy (fun c -> c.Country.ToString())