Scala 转换集到地图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4851418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala Convert Set to Map
提问by Torsten Schmidt
How do I convert a Set("a","b","c") to a Map("a"->1,"b"->2,"c"->3)? I think it should work with toMap.
如何将 Set("a","b","c") 转换为 Map("a"->1,"b"->2,"c"->3)?我认为它应该与 toMap 一起使用。
回答by Adam Rabung
zipWithIndexis probably what you are looking for. It will take your collection of letters and make a new collection of Tuples, matching value with position in the collection. You have an extra requirement though - it looks like your positions start with 1, rather than 0, so you'll need to transform those Tuples:
zipWithIndex可能是您正在寻找的。它将获取您的字母集合并创建一个新的元组集合,将值与集合中的位置相匹配。不过你有一个额外的要求——看起来你的位置从 1 开始,而不是 0,所以你需要转换这些元组:
Set("a","b","c")
.zipWithIndex //(a,0), (b,1), (c,2)
.map{case(v,i) => (v, i+1)} //increment each of those indexes
.toMap //toMap does work for a collection of Tuples
One extra consideration - Sets don't preserve position. Consider using a structure like List if you want the above position to consistently work.
一个额外的考虑 - 集合不保留位置。如果您希望上述职位始终有效,请考虑使用类似 List 的结构。
回答by Frank S. Thomas
回答by GClaramunt
toMaponly works if the Setentries are key/value pairs (e.g. Set(("a",1),("b",2),("c",3))).
toMap仅当Set条目是键/值对时才有效(例如Set(("a",1),("b",2),("c",3)))。
To get what you want, use zipWithIndex:
要获得您想要的东西,请使用zipWithIndex:
Set("a","b","c") zipWithIndex
// Set[(String, Int)] = Set((a,0), (b,1), (c,2))
or (as in you original question):
或(如你原来的问题):
Set("a","b","c") zip (1 to 3) toMap
回答by Viktor Nordling
This would also work:
这也可以:
(('a' to 'c') zip (1 to 3)).toMap

