列表列表:如何为除最后一个列表之外的每个列表添加尾随 0?

List of Lists: how to add a trailing 0 for each List except the last one?

列表列表:如何为除最后一个列表之外的每个列表添加尾随 0?

我正在学习 Scala。我有一个列表列表,如下所示:

List(List(1,2,3), List(15, 17, 21), List(28, 5, 7))

我的目标是为除最后一个列表之外的每个列表添加尾随 0,如下所示:

List(List(1,2,3, 0), List(15, 17, 21, 0), List(28, 5, 7))

我的解决方案如下:

def addZero(lines: List[List[Int]]): List[Int] = {
     def helper(nums: List[Int]): List[Int] = nums match {
       case Nil => 0 :: Nil
       case hd :: tl => hd :: helper(tl)
     }

     lines match {
       case Nil => Nil
       case hd :: Nil => hd
       case hd :: tl => helper(hd) ++ addZero(tl)
     }
}

但我不确定是否有更优雅的方式。我尝试了 flatMapfoldLeft 但他们将 0 添加到每个列表 包括最后一个。

你可以这样做:

List(List(1, 2, 3), List(15, 17, 21), List(28, 5, 7)) match {
  case begin :+ last => begin.map(_ :+ 0) :+ last
}

详细说明:您首先对列表列表进行模式匹配,以便轻松提取列表中不是最后一个的元素。

"begin" represents List(List(1, 2, 3), List(15, 17, 21))
"last" represents List(28, 5, 7)

然后在每个列表的最后位置添加 0

_ :+ 0 // List(15, 17, 21) => List(15, 17, 21, 0)

最后添加最后一个元素

  list.init.map { _ :+ 0 } :+ list.last