如果我说我有
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))我试过滑行,但没有起作用。有人能给我指明正确的方向吗。
发布于 2017-11-12 17:50:43
这有点棘手,我认为最好的方法是使用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发布于 2017-11-12 18:28:14
我意识到使用sliding要容易得多,因为您提出了您的问题
ll.sliding(2).map{
case List(l1, l2) =>
l1.zip(l2).map{
case (v1, v2)=> v1 * v2
}
}.toListhttps://stackoverflow.com/questions/47251900
复制相似问题