如何合并两个列表/ Seq
,以便它从列表1中获取1个元素,然后从列表2中获取1个元素,依此类推,而不是仅在列表1的末尾附加列表2? / p>
例如
[1,2] + [3,4] = [1,3,2,4]
而不是[1,2,3,4]
有什么想法吗?我看过的大多数concat
方法似乎都是针对后者,而不是针对前者。
答案 0 :(得分:5)
您可以这样做:
val l1 = List(1, 2)
val l2 = List(3, 4)
l1.zip(l2).flatMap { case (a, b) => List(a, b) }
答案 1 :(得分:5)
另一种方式:
List(List(1,2), List(3,4)).transpose.flatten
答案 2 :(得分:5)
因此,您的收藏可能并不总是相同的大小。在这种情况下使用zip
会造成数据丢失。
def interleave[A](a :Seq[A], b :Seq[A]) :Seq[A] =
if (a.isEmpty) b else if (b.isEmpty) a
else a.head +: b.head +: interleave(a.tail, b.tail)
interleave(List(1, 2, 17, 27)
,Vector(3, 4)) //res0: Seq[Int] = List(1, 3, 2, 4, 17, 27)
答案 3 :(得分:4)
尝试
List(1,2)
.zip(List(3,4))
.flatMap(v => List(v._1, v._2))
输出
res0: List[Int] = List(1, 3, 2, 4)
还要考虑以下隐式类
implicit class ListIntercalate[T](lhs: List[T]) {
def intercalate(rhs: List[T]): List[T] = lhs match {
case head :: tail => head :: (rhs.intercalate(tail))
case _ => rhs
}
}
List(1,2) intercalate List(3,4)
List(1,2,5,6,6,7,8,0) intercalate List(3,4)
输出
res2: List[Int] = List(1, 3, 2, 4)
res3: List[Int] = List(1, 3, 2, 4, 5, 6, 6, 7, 8, 0)