在Scala中,是否有办法将两个列表转换成Map? [英] In Scala, is there a way to take convert two lists into a Map?
问题描述
我有两个列表,一个List[A]
和List[B]
.我想要的是Map[A,B]
,但我想要zip
的语义.所以开始像这样:
I have a two lists, a List[A]
and a List[B]
. What I want is a Map[A,B]
but I want the semantics of zip
. So started out like so:
var tuplesOfAB = listOfA zip listOfB
现在我不确定如何从我的tuplesOfAB
构造一个Map
.
Now I'm not sure how to construct a Map
from my tuplesOfAB
.
作为后续问题,我还想反转地图,以便从Map[A,B]
创建一个Map[B,A]
.有人可以用线索棒打我吗?
As a follow-up question, I also want to invert my map so that from a Map[A,B]
I can create a Map[B,A]
. Can anyone hit me with a clue-stick?
推荐答案
In 2.8 this is really simple using the CanBuildFrom
functionality (as described by Daniel) and using breakOut
with a type instruction to the compiler as to what the result type should be:
import scala.collection.breakOut
val m = (listA zip listB)(breakOut): Map[A,B]
以下内容也可以工作:
val n: Map[A,B] = (listA zip listB)(breakOut)
并且(如下面的EastSun所指出的那样),该代码已作为toMap
And (as EastSun, below, has pointed out) this has been added to the library as toMap
val o = (listA zip listB).toMap
关于反转地图,您可以执行以下操作:
As for reversing the map, you can do:
val r = m.map(_.swap)(breakOut): Map[B, A]
这篇关于在Scala中,是否有办法将两个列表转换成Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!