如何从scala中的列表生成元组数组?

时间:2014-12-19 11:46:55

标签: scala

我有一行如下(Int,List(String))

(22,List(B00000JCDS, B000004CSZ, B00016XN6Q, B00005LLY3, B00023B1UI))

我需要生成一个元组数组或任何其他集合,如下所示:

(22,B00000JCDS)
(22,B000004CSZ)
(22,B00016XN6Q)
(22,B00005LLY3)
(22,B00023B1UI)

如何在Scala中生成此数据集?

3 个答案:

答案 0 :(得分:4)

scala> a._2.map((a._1,_))
res3: List[(Int, String)] = List((22,B00000JCDS), (22,B000004CSZ), (22,B00016XN6Q), (22,B00005LLY3), (22,B00023B1UI))

其中a为(22,List(B00000JCDS, B000004CSZ, B00016XN6Q, B00005LLY3, B00023B1UI))

答案 1 :(得分:1)

最让人想到的是使用for理解:

scala>   val g = (22,List("B00000JCDS", "B000004CSZ", "B00016XN6Q", "B00005LLY3", "B00023B1UI"))
g: (Int, List[String]) = (22,List(B00000JCDS, B000004CSZ, B00016XN6Q, B00005LLY3, B00023B1UI))

scala>   
   |   for {
   |     fromList <- g._2
   |   } yield (g._1, fromList)

res3: List[(Int, String)] = List((22,B00000JCDS), (22,B000004CSZ), (22,B00016XN6Q), (22,B00005LLY3), (22,B00023B1UI))

如果你想要一个数组,只需拨打toArray

答案 2 :(得分:0)

针对给定行a的几种方法,如下所示,

Array.fill(a._2.size)(a._1) zip a._2

(Iterator.continually(a._1) zip a._2.iterator) toArray

Array.tabulate(a._2.size)(i => (a._1, a._2(i)) )