F#:迭代字典只返回自己? [英] F#: Iterating over a dictionary just returns itself?

查看:199
本文介绍了F#:迭代字典只返回自己?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  let h = dict [(1,2),(3,4)] 
Console.WriteLine(h.Count)

Console.WriteLine(i)

给我

  1 
[(1,2),(3,4)]

两个问题。首先,为什么迭代一个字典给我一个只有1个项目的序列,dict本身?这可能有一些逻辑,也将影响我最终尝试迭代的其他事情。对于由any(),All(),Aggregate()等暴露的所有其他Seq成员,这意味着什么)?



其次,是否有很好的迭代方式,通常会在字典中操作键值对,就像Python一样?

解决方案

您使用逗号分配分号。

  [(1,2); (3,4)] 

元组的逗号,列表元素的分号。 (这里的括号是可选的。)



如果要迭代字典中的键值对,可以使用



$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $

使用 KeyValue 活动模式。


let h = dict [(1, 2), (3, 4)]
Console.WriteLine(h.Count)
for i in h do
    Console.WriteLine(i)

gives me

1
[(1, 2), (3, 4)]

Two questions. Firstly, why does iterating over a dict give me back a sequence which only has 1 item, the dict itself? There is probably some logic behind this that will also affect other things I end up trying to iterate over. What does this mean for all the other Seq members exposed by dict (Any(), All(), Aggregate(), etc.)?

Secondly, is there a good way to iterate over and generally manipulate the key-value pairs in the dictionary, like in Python?

解决方案

You used a comma where you need a semicolon.

[(1,2); (3,4)]

Commas for tuples, semicolons for list elements. (The parens here are optional.)

If you want to iterate over key-value pairs in the dictionary, you can use

for KeyValue(k,v) in someDictionary do ...

which uses the KeyValue active pattern.

这篇关于F#:迭代字典只返回自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆