我开始学习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}}
Run Code Online (Sandbox Code Playgroud)
然后有一个功能
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
Run Code Online (Sandbox Code Playgroud)
例如,使用以下参数调用此函数
sim_distance(dicoOfItems, 'aaaaa', 'bbbbb')
Run Code Online (Sandbox Code Playgroud)
我的问题是我怎么能获得一个新的字典做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"]
Run Code Online (Sandbox Code Playgroud)
正如John Palmer所指出的,在F#中的单个语句中创建字典的适当方法是使用dict获取序列类型并将其转换为字典的函数.
dict;;
val it : (seq<'a * 'b> -> IDictionary<'a,'b>) when 'a : equality = <fun:clo@3>
Run Code Online (Sandbox Code Playgroud)
注意
[for x in [1..10] do
if x%2 = 0 then
yield x.ToString(),x]
Run Code Online (Sandbox Code Playgroud)
创建一个列表([]是列表符号,列表是序列),然后该列表是函数的参数,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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
363 次 |
| 最近记录: |