简体   繁体   English

F#中的Python风格集合

[英]Python-style collections in F#

I'm trying to refactor some python code which I'm using for financial analytics processing into F#, and I'm having difficulty in replicating some of my beloved Python datatypes. 我正在尝试将我用于财务分析处理的一些python代码重构为F#,并且我很难复制一些我心爱的Python数据类型。 For instance in Python I could happily declare a variable like this: 例如在Python中,我可以愉快地声明一个这样的变量:

timeSeries = { "20110131":1.5, "20110228":1.5, "20110331":1.5, 
               "20110431":1.5, "20110531":1.5 }

And then throw it around between functions but I don't know the equivalent in F#. 然后在函数之间抛出它,但我不知道F#中的等价物。 I've tried this: 我试过这个:

let timeSeries = ( ["20110131":1.5], ["20110228":1.5], ["20110331":1.5], 
                   ["20110431":1.5], ["20110531":1.5] )

But of course it fails... I'm aware that somebody out there is probably spluttering with laughter, but I'm very new to F# and it feels constrictive compared to Python. 但当然它失败了...我知道那里的人可能会大笑起来,但我对F#很新,与Python相比它感觉更加紧缩。

I'm familiar with .NET as well, it's just that F# seems to sit somewhere between scripting and "proper" languages like C# and I haven't quite grokked how to use it effectively yet - everything takes ages. 我也熟悉.NET,只是F#似乎介于脚本和C#之类的“正确”语言之间,我还没有完全理解如何有效地使用它 - 一切都需要很长时间。

To be honest, your dictionary declaration in Python doesn't look much different from what you can declare in F#: 老实说,你在Python中的字典声明与你在F#中声明的内容没什么不同:

let timeSeries = dict [
             "20110131", 1.5; // ',' is tuple delimiter and ';' is list delimiter
             "20110228", 1.5;
             "20110331", 1.5; 
             "20110431", 1.5; 
             "20110531", 1.5; // The last ';' is optional
             ]

Because : is used for type annotation in F#, you couldn't redefine it. 因为:用于F#中的类型注释,您无法重新定义它。 But you can create a custom infix operator to make the code more readable and closer to what you usually do in Python: 但是您可以创建一个自定义中缀运算符,使代码更具可读性,更接近您在Python中通常所做的操作:

let inline (=>) a b = a, b

let timeSeries = dict [
         "20110131" => 1.5;
         "20110228" => 1.5;
         "20110331" => 1.5; 
         "20110431" => 1.5; 
         "20110531" => 1.5;
         ]

You may find this answer helpful. 您可能会发现此答案很有帮助。 It looks like you want a dictionary. 看起来你想要一本字典。 In case you don't already know, F# supports something akin to Python's generator expressions, called sequence expressions [MSDN] , which you may also find useful. 如果您还不知道,F#支持的东西类似于Python的生成器表达式,称为序列表达式[MSDN] ,您可能也会发现它很有用。 For example: 例如:

let d = dict [ for i in 0 .. 10 -> i, -i ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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