Scala—查找列表中当前元素的确切索引

Scala—查找列表中当前元素的确切索引,scala,for-loop,indexof,Scala,For Loop,Indexof,在这个for循环中,我试图找出索引10(最后一个元素)时遇到了一个问题 比如说 val l: List[Int] = List(10, 1, 4, 5, 6, 10) for(i <- l) { println(i + " " + l.indexOf(i)) } 如何在最后一行中获取105 List(10, 1, 4, 5, 6, 10).zipWithIndex.foreach{ case(a, b) => println(a + " " + b)} > 10 0

在这个for循环中,我试图找出索引10(最后一个元素)时遇到了一个问题

比如说

val l: List[Int] = List(10, 1, 4, 5, 6, 10)
for(i <- l)
{
   println(i + " " + l.indexOf(i))
}
如何在最后一行中获取
105

List(10, 1, 4, 5, 6, 10).zipWithIndex.foreach{ case(a, b) => println(a + " " + b)}
> 10 0
  1 1
  4 2
  5 3
  6 4
  10 5

您可以使用
zipWithIndex
生成
value
index

您可以使用一个范围进行迭代:

let tempL = l;
let el;
for (i <- 0 until l.length) {
    el = tempL.head;
    prinln(i + " " + el);
    tempL = tempL.tail
}
让temp=l;
让el;
对于(i
vall:List[Int]=List(10,1,4,5,6,10)

for((v,i)可能最容易采用递归方法进行列表分解,在已经处理的索引数量上保持累加器
let tempL = l;
let el;
for (i <- 0 until l.length) {
    el = tempL.head;
    prinln(i + " " + el);
    tempL = tempL.tail
}
val l: List[Int] = List(10, 1, 4, 5, 6, 10)

for((v, i) <- l.zipWithIndex) {
  println(v + " " + l.indexOf(v, i))
}