Scala-以交替方式合并两个列表 [英] Scala - Combine two lists in an alternating fashion

查看:86
本文介绍了Scala-以交替方式合并两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何以这样的方式合并2个列表,使得结果列表在Scala中以交替的方式包含2个列表的元素.

How do I merge 2 lists in such a way that the resulting list contains the elements of 2 lists in alternating fashion in Scala.

输入:

val list1 = List("Mary", "a", "lamb")

val list2 = List("had", "little")

输出:

List("Mary", "had", "a", "little", "lamb")

推荐答案

您正在寻找的东西通常称为"intersperse"或"intercalate",并且有几种方法可以实现:

What you're looking for is usually called "intersperse" or "intercalate" and there are a few ways to do it:

def intersperse[A](a : List[A], b : List[A]): List[A] = a match {
  case first :: rest => first :: intersperse(b, rest)
  case _             => b
}

您也可以使用scalaz

import scalaz._
import Scalaz._

val lst1 = ...
val lst2 = ...

lst1 intercalate lst2

编辑:您还可以执行以下操作:

Edit: You can also do the following:

lst1.zipAll(lst2,"","") flatMap { case (a, b) => Seq(a, b) }

请考虑一下,我相信最后一个解决方案是我的最爱,因为它最简洁,同时仍然很清晰.如果您已经在使用Scalaz,我将使用第二种解决方案.但是,第一个也很可读.

Come to think of it, I believe the last solution is my favorite since it's most concise while still being clear. If you're already using Scalaz, I'd use the second solution. The first is also very readable however.

为了使这个答案更完整,添加了@Travis Brown的通用解决方案:

And just to make this answer more complete, adding @Travis Brown's solution that is generic:

list1.map(List(_)).zipAll(list2.map(List(_)), Nil, Nil).flatMap(Function.tupled(_ ::: _))

这篇关于Scala-以交替方式合并两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆