在 Scala 中,有没有办法将两个列表转换为 Map?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2189784/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 01:54:07  来源:igfitidea点击:

In Scala, is there a way to take convert two lists into a Map?

listscalamapscala-2.8tuples

提问by Andy Hull

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:

我有两个列表,一个List[A]和一个List[B]。我想要的是 aMap[A,B]但我想要zip. 所以开始是这样的:

var tuplesOfAB = listOfA zip listOfB

Now I'm not sure how to construct a Mapfrom my tuplesOfAB.

现在我不确定如何Map从我的tuplesOfAB.

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?

作为后续问题,我还想反转我的地图,以便从Map[A,B]我可以创建一个Map[B,A]. 有人可以用线索棒打我吗?

回答by oxbow_lakes

In 2.8this is really simple using the CanBuildFromfunctionality (as described by Daniel) and using breakOutwith a type instructionto the compiler as to what the result type should be:

2.8 中,使用CanBuildFrom功能(如 Daniel 所述)和使用breakOut类型指令给编译器关于结果类型应该是什么非常简单:

import scala.collection.breakOut
val m = (listA zip listB)(breakOut): Map[A,B]

The following would also work:

以下也将起作用:

val n: Map[A,B] = (listA zip listB)(breakOut)

And (as EastSun, below, has pointed out) this has been added to the library as toMap

并且(正如下面的 EastSun 指出的那样)这已被添加到库中 toMap

val o = (listA zip listB).toMap

As for reversing the map, you can do:

至于反转地图,你可以这样做:

val r = m.map(_.swap)(breakOut): Map[B, A]

回答by Geoff Reedy

Now that you've got a list of tuples it is easy to make it into a map by writing Map(tuplesOfAB: _*). The : _*notation means to call the varargs overload with the arguments taken from the sequence. This seems like a funny bit of syntax, but it helps to think that varargs are declared like Map[A,B](pairs: (A,B)*)and the : _*is a type annotation to convert to varargs because of the common *part.

现在您已经有了一个元组列表,很容易通过编写Map(tuplesOfAB: _*). 该: _*表示法意味着使用从序列中获取的参数调用 varargs 重载。这似乎是一个有趣的语法,但它有助于认为 varargs 被声明为 likeMap[A,B](pairs: (A,B)*)并且: _*由于公共*部分,the is a type annotation to convert to varargs 。

To reverse a map muse Map(m.map(_.swap): _*). In scala a map is also a collection of pairs. This transforms those pairs by swapping the elements and passing them to the Map constructor.

要反转地图,请m使用Map(m.map(_.swap): _*). 在 Scala 中,地图也是对的集合。这通过交换元素并将它们传递给 Map 构造函数来转换这些对。

回答by Daniel C. Sobral

There's yet another way to do it, beyond those already shown. Here:

除了已经展示的方法之外,还有另一种方法可以做到这一点。这里:

Map() ++ tuplesOfAB

回答by Ashwin

scala> List( "a", "f", "d") zip List(7, 5, 4, 8) toMap
res0: scala.collection.immutable.Map[java.lang.String,Int] = Map(a -> 7, f -> 5, d -> 4)