【问题标题】:How to merge two Seq[String], Seq[Double] to Seq[(String,Double)]如何将两个 Seq[String]、Seq[Double] 合并到 Seq[(String,Double)]
【发布时间】:2017-12-29 10:56:13
【问题描述】:

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

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

我想创建输出为

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

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

谁能建议如何在 scala 中做到这一点?

【问题讨论】:

  • a.zip(b).toMap

标签: scala seq


【解决方案1】:

您只需要.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?

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    • 2020-08-12
    • 2018-06-29
    相关资源
    最近更新 更多