Menu
CoddyTech

WithIndex 方法

本课属于 Coddy Kotlin 学习旅程的“基础知识”单元。第 75 课,共 93 课。

遍历列表时,你通常不仅需要知道元素,还需要知道它的位置。withIndex() 方法可以一次性提供这两者。

对任意列表调用 withIndex(),即可获得由索引和值组成的键值对:

val colors = listOf("Red", "Green", "Blue")
for ((index, color) in colors.withIndex()) {
    println("$index: $color")
}
// 输出:
// 0: Red
// 1: Green
// 2: Blue

注意括号内的语法:(index, color)。这叫作解构,它会将索引和值拆分到单独的变量中。你可以根据代码的需要为这些变量命名。

与手动使用计数器变量跟踪索引相比,这种方法更简洁。尤其是在你需要显示带编号的列表,或根据位置执行不同操作时,这种方法很有用:

val tasks = listOf("Wake up", "Exercise", "Eat breakfast")
for ((i, task) in tasks.withIndex()) {
    println("Step ${i + 1}: $task")
}
// 输出:
// Step 1: Wake up
// Step 2: Exercise
// Step 3: Eat breakfast
challenge icon

挑战

中等

输入中会提供一个学生姓名列表。先读取学生人数,再读取每个姓名。

使用 withIndex(),为每个学生打印对应的排名(从 1 开始,而不是从 0 开始)。

输入格式:

  • 第一行:一个整数 n,表示学生人数
  • 接下来的 n 行:学生姓名(字符串)

输出格式:

每行打印一名学生,格式如下:

Rank 1: Alice
Rank 2: Bob
Rank 3: Charlie

请记住,withIndex() 提供的索引从 0 开始,因此你需要调整排名,使其从 1 开始。

亲手试试

fun main() {
    // 读取学生人数
    val n = readLine()!!.toInt()
    
    // 将学生姓名读入列表
    val students = mutableListOf<String>()
    for (i in 1..n) {
        students.add(readLine()!!)
    }
    
    // TODO:在下面编写你的代码
    // 使用 withIndex() 遍历 students 并输出每位学生的名次
    // 记住:withIndex() 的索引从 0 开始,但名次应从 1 开始
    
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

基础知识中的所有课

自己练习: Kotlin 在线编辑器