本文介绍了用默认元素来填充两个不同长度的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有以下不同大小的列表:

  val list1 =(a,b, c)
val list2 =(x,y)

想要合并这两个列表并创建一个新的列表,并将字符串元素连接起来:

  val desiredResult =(ax, by,c)

我试过了

  val wrongResult =(list1,list2).zipped map(_ + _)

建议,但是这个因为zip会丢弃无法匹配的较长列表中的元素。



我该如何解决这个问题?有一种方法可以压缩列表并给出一个默认元素(如本例中的空字符串),如果一个列表更长? div>

您正在寻找的方法是:

  scala> val list1 = List(a,b,c)
list1:List [String] = List(a,b,c)

scala> val list2 = List(x,y)
list2:List [String] = List(x,y)

scala> list1.zipAll(list2,,)
res0:List [(String,String)] = List((a,x),(b,y),(c,))






.zipAll


  • 可压缩的迭代

  • 缺省值if this (集合 .zipAll 被调用)更短

  • 默认价值,如果其他集合较短


Assume we have the following lists of different size:

val list1 = ("a", "b", "c")
val list2 = ("x", "y")

Now I want to merge these 2 lists and create a new list with the string elements being concatenated:

val desiredResult = ("ax", "by", "c")

I tried

val wrongResult = (list1, list2).zipped map (_ + _)

as proposed here, but this doesn't work as intended, because zip discards those elements of the longer list that can't be matched.

How can I solve this problem? Is there a way to zip the lists and give a "default element" (like the empty string in this case) if one list is longer?

解决方案

The method you are looking for is .zipAll:

scala> val list1 = List("a", "b", "c")
list1: List[String] = List(a, b, c)

scala> val list2 = List("x", "y")
list2: List[String] = List(x, y)

scala> list1.zipAll(list2, "", "")
res0: List[(String, String)] = List((a,x), (b,y), (c,""))


.zipAll takes 3 arguments:

  • the iterable to zip with
  • the default value if this (the collection .zipAll is called on) is shorter
  • the default value if the other collection is shorter

这篇关于用默认元素来填充两个不同长度的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 13:58