[英]F# dictionary initialization like in Python
我開始學習F#,並且在嘗試找出簡單的東西時遇到了一些困難。 我有一個想要轉換為F#的python代碼。 問題是我不真正知道如何轉換為F#的python中字典的初始化。
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 ?
我嘗試在f。Seq.exists中使用.if列表語法的Python if ..但后來我不知道如何初始化新字典。
我玩過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
因此,我認為您想使用可變的System.Collections.Generic.Dictionary<_,_>
而不是不變的F# dict
。 您將按以下方式使用它:
let sim_distance(prefs:System.Collections.Generic.IDictionary<_,_>,person1,person2) =
let si= System.Collections.Generic.Dictionary<_,_>()
for KeyValue(k,v) in prefs.[person1] do
for KeyValue(k2,v2) in prefs.[person2] do if k2=k then si.Add(k,1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.