Scala从当前项获取列表中的下一个索引
比如说,我正在将一个列表映射到下一个列表,在映射中,我想用列表中的当前项和列表中的下一项进行一些计算Scala从当前项获取列表中的下一个索引,scala,Scala,比如说,我正在将一个列表映射到下一个列表,在映射中,我想用列表中的当前项和列表中的下一项进行一些计算 def someFunc(L: List[Integer]) : List[Integer] = { L.collect { case k if (k != L(L.length-1)) //do something with k and the next element } } 一个简单的例子是,我想遍历这个整数列表,并将每个数字映射到列表中除以它的下一个数
def someFunc(L: List[Integer]) : List[Integer] = {
L.collect {
case k if (k != L(L.length-1)) //do something with k and the next element
}
}
一个简单的例子是,我想遍历这个整数列表,并将每个数字映射到列表中除以它的下一个数字上
例如:(1,2,3)->(2/1,3/2)==(2,1.5)
我曾想过使用indexOf进行此操作,但我认为在整个列表中搜索当前元素并不有效,即使我已经遍历了列表中的每个元素。使用
。滑动进行此操作:
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> l.sliding(2).toList
res0: List[List[Int]] = List(List(1, 2), List(2, 3))
scala> l.sliding(2).collect { case x::y::Nil if y != 0 => x / y.toDouble }.toList
res1: List[Double] = List(0.5, 0.6666666666666666)
为此使用.slideing
:
scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)
scala> l.sliding(2).toList
res0: List[List[Int]] = List(List(1, 2), List(2, 3))
scala> l.sliding(2).collect { case x::y::Nil if y != 0 => x / y.toDouble }.toList
res1: List[Double] = List(0.5, 0.6666666666666666)
x和y的顺序不对,应该是y/x
,但逻辑是正确的。谢谢你把x和y的顺序弄错了,应该是y/x
,但是逻辑是正确的。谢谢