简体   繁体   English

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

[英]F# dictionary initialization like in Python

I'm starting to learn F# and I'm having some hard times trying to figure out simple things. 我开始学习F#,并且在尝试找出简单的东西时遇到了一些困难。 I have a python code that I would like to convert to F#. 我有一个想要转换为F#的python代码。 The problem is the initialization of dictionaries in python that I don't really know how to convert to F#. 问题是我不真正知道如何转换为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}}

then there is a function 然后有一个功能

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

this function is called with the following parameters for example 例如,使用以下参数调用此函数

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

My question is how I could do the same in F# for obtaining a new dictionary si ? 我的问题是如何在F#中做同样的事情以获得新的字典si

The Python if .. in .. list syntax I tried to use with f# Seq.exists but then I didn't know how to initialize the new dictionary. 我尝试在f。Seq.exists中使用.if列表语法的Python if ..但后来我不知道如何初始化新字典。

I've played with Seq.choose, Seq.map but with no success. 我玩过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"]

As John Palmer noted, the appropriate way to create a dictionary in a single statement in F# is to use the dict function which takes a sequence type and converts it to a dictionary. 正如John Palmer指出的那样,在F#中的单个语句中创建字典的适当方法是使用dict函数,该函数采用序列类型并将其转换为字典。

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

Note that 注意

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

creates a list ([] is list notation and lists are sequences), and then that list is the parameter to the function dict which converts it to a dictionary. 创建一个列表([]是列表符号,列表是序列),然后该列表是函数dict的参数,该函数将其转换为字典。

Your function would then look like this: 您的函数将如下所示:

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

So I think you want to use the System.Collections.Generic.Dictionary<_,_> which is mutable rather than the F# dict which is immutable. 因此,我认为您想使用可变的System.Collections.Generic.Dictionary<_,_>而不是不变的F# dict You would use it as follows: 您将按以下方式使用它:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM