Skip to main content
 首页 » 编程设计

python之F# 字典初始化就像在 Python 中一样

2025年05月04日12mq0036

我开始学习 F#,但在尝试弄清楚简单的事情时遇到了一些困难。我有一个 python 代码,我想将其转换为 F#。问题是在 python 中初始化字典,我真的不知道如何转换为 F#。

dicoOfItems = {'aaaaa': {'a': 2.5, 'b': 3.5, 'c': 3.0, 'd': 3.5, 'e': 2.5,'f': 3.0}, 'bbbbb': {'a': 3.0, 'b': 3.5}} 

还有一个函数

def sim_distance(prefs,person1,person2): 
 si={} // I want the same in F# 
  for item in prefs[person1]:  
    if item in prefs[person2]: si[item]=1 
 
 // do stuff 
return something 

此函数使用以下参数调用,例如

sim_distance(dicoOfItems, 'aaaaa', 'bbbbb') 

我的问题是如何在 F# 中执行相同操作以获取新字典 si?

我尝试将 Python if .. in .. list 语法与 f# Seq.exists 一起使用,但后来我不知道如何初始化新字典。

我玩过 Seq.choose、Seq.map 但没有成功。

请您参考如下方法:

let test = dict [for x in [1..10] do 
                     if x%2 = 0 then 
                         yield x.ToString(),x] //note that this is returning a (string*int) 
printfn "%d" test.["5"] 

正如 John Palmer 指出的那样,在 F# 中的单个语句中创建字典的适当方法是使用 dict 函数,该函数采用序列类型并将其转换为字典。

dict;; 
val it : (seq<'a * 'b> -> IDictionary<'a,'b>) when 'a : equality = <fun:clo@3> 

注意

[for x in [1..10] do 
     if x%2 = 0 then 
         yield x.ToString(),x] 

创建一个列表([] 是列表表示法,列表是序列),然后该列表是函数 dict 的参数,将其转换为字典。

你的函数看起来像这样:

let sim_distance prefs person1 person2 = 
    let si=dict [for item in prefs.[person1] do 
                     if prefs.[person2].Contains(item) then  
                         yield item,1] 
    something