我在F#中有一系列国家/地区名称.我想知道序列中每个不同的国家/地区条目有多少.
Microsoft docs和MSDN中的countBy示例使用if
并else
获取Keys,但由于我有大约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
Run Code Online (Sandbox Code Playgroud)
任何对我的city.list.json感兴趣的人
更新
我的输入序列是这样的(包含更多条目),每个代码重复,因为该国家/地区的许多城市都在原始列表中:
{ "AR","MX","RU","US"}
Run Code Online (Sandbox Code Playgroud)
结果我期望:
{("AR", 50),("MX",40),...}
Run Code Online (Sandbox Code Playgroud)
The*_*Fox 10
Countries |> Seq.countBy id
Run Code Online (Sandbox Code Playgroud)
id
是身份功能fun x -> x
.使用它,因为这里的"键"是序列项本身.
您可以对国家/地区进行分组,然后计算每个组中的条目数:
let countsByCountry =
Countries
|> Seq.groupBy id
|> Seq.map (fun (c, cs) -> c, Seq.length cs)
Run Code Online (Sandbox Code Playgroud)
此组合也作为单个函数实现,countBy
:
let countsByCountry = Countries |> Seq.countBy id
Run Code Online (Sandbox Code Playgroud)
那么,是否可以选择使用另一个序列来获取 countBy 的键?
您不需要从某处获取密钥,传递给Seq.countBy
生成密钥的函数。你应该能够摆脱这个:
let count =
cities
|> Seq.countBy (fun c -> c.Country.ToString())
Run Code Online (Sandbox Code Playgroud)