如何将两个Seq [String],Seq [Double]合并为Seq [(String,Double)]

时间:2017-07-23 23:14:56

标签: scala seq

我有两个Seq。 1有Seq[String],另有Seq[(String,Double)]

a -> ["a","b","c"]b-> [1,2,3]

我想将输出创建为

[("a",1),("b",2),("c",3)]

我有一个代码 a.zip(b)实际上是在创建这两个元素的seq而不是创建地图

有人可以建议如何在scala中执行此操作吗?

1 个答案:

答案 0 :(得分:2)

您只需要.toMap,以便将List[Tuple[String, Int]]转换为Map[String, Int]

scala> val seq1 = List("a", "b", "c")
seq1: List[String] = List(a, b, c)

scala> val seq2 = List(1, 2, 3)
seq2: List[Int] = List(1, 2, 3)

scala> seq1.zip(seq2)
res0: List[(String, Int)] = List((a,1), (b,2), (c,3))

scala> seq1.zip(seq2).toMap
res1: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)

也见

How to convert a Seq[A] to a Map[Int, A] using a value of A as the key in the map?