如何使用scala组合两个列表?

时间:2015-01-09 11:12:34

标签: scala

我有以下列表 -

val A = List(("A","B","C","D"),("A1","B1","C1","D1"),("A2","B2","C2","D2"))

val B = List(("P","Q","R","S","T"),("P1","Q1","R1","S1","T1"),("P2","Q2","R2","S2","T2"),("P3","Q3","R3","S3","T3"))

我想将列表A的第一个元素与列表B的第一个元素合并,依此类推。 这里列表A有3个元素,B有4个。我想在合并时考虑列表A中的元素数。

输出如下

val combineList = List(("A","B","C","D","P","Q","R","S","T"),("A1","B1","C1","D1","P1","Q1","R1","S1","T1"),
        ("A2","B2","C2","D2","P2","Q2","R2","S2","T2"))

3 个答案:

答案 0 :(得分:7)

如果你可以使用无形,那么你可以简单地做

scala> import shapeless.syntax.std.tuple._
scala> A.zip(B).map{case(a,b) => a ++ b}
res1: List[(String, String, String, String, String, String, String, String, String)] = List((A,B,C,D,P,Q,R,S,T), (A1,B1,C1,D1,P1,Q1,R1,S1,T1), (A2,B2,C2,D2,P2,Q2,R2,S2,T2))

它适用于任意大小的元组。

答案 1 :(得分:1)

A.zip(B).map { case ((a,b,c,d), (p,q,r,s,t)) => (a,b,c,d,p,q,r,s,t) }

答案 2 :(得分:-1)

sequnces中的第一个拉链元组:

val lists = for {i <- 0 until A.length
     a = A(i)
     b = B(i)
} yield (a.productIterator ++ b.productIterator).toList

接下来将转换器从Seq定义回Product

def toTuple(seq: Seq[_]): Product = {
  val clz = Class.forName("scala.Tuple" + seq.size)
  clz.getConstructors()(0).newInstance(seq.map(_.asInstanceOf[AnyRef]): _*).asInstanceOf[Product]
}

最后做map

lists.map(toTuple)

此代码不考虑输入列表的不同和元组大小的限制。