Scala 更改 2D 列表和 return 新列表中的数据

Scala change data iniside 2D list and return new list

如果我有

val ll : List[List[Int]] = List(List(1,2,3), List(4,5,6), List(7,8,9))

我想做的是将列表中的每个数字与下一个数字相乘。所以 n 到 n+1 乘法。

所以我想做的是 1 乘 4、2 乘 5、3 乘 6、4 乘 7、5 乘 8 和 6 乘 9。

val x : List[List[Int]] = List(List(4,10,18), List(28,40,54))

我试过滑动(2)但是没用。有人能给我指出正确的方向吗?

这有点棘手,我认为最好的方法是使用 foldLeft

// we need to iterate on the list saving the previous element so we can use it for the multiplication. We start the iteration from the second element and we use the head as the first previous element
ll.tail.foldLeft((List[List[Int]](), ll.head)) {
   case ((res, last), elem) =>
     // here we calculate the multiplication
     val mult = elem.zip(last).map{
       case (v1, v2) => v1 * v2
     }
     // we add it to the result and we update the previous element
     (mult :: res, elem)
}._1.reverse

foldRight

ll.dropRight(1).foldRight((List[List[Int]](), ll.last)) {
   case (elem, (res, last)) =>
     val mult = elem.zip(last).map{
       case (v1, v2) => v1 * v2
     }
     (mult :: res, elem)
}._1

我意识到使用 sliding 更容易,正如您提出的问题

ll.sliding(2).map{
    case List(l1, l2) => 
       l1.zip(l2).map{ 
          case (v1, v2)=> v1 * v2 
       }
}.toList