Kotlin有像Python这样的"枚举"函数吗?

faf*_*afl 16 list enumerate kotlin

在Python中我可以写:

for i, element in enumerate(my_list):
    print i          # the index, starting from 0
    print element    # the list-element
Run Code Online (Sandbox Code Playgroud)

我怎么能在Kotlin写这个?

zsm*_*b13 23

forEachIndexed标准库中有一个函数:

myList.forEachIndexed { i, element ->
    println(i)
    println(element)
}
Run Code Online (Sandbox Code Playgroud)

请参阅@ s1m0nw1的答案,withIndex也是一种非常好的迭代方法Iterable.


s1m*_*nw1 20

Kotlin中的迭代:一些替代品

  1. 就像已经说过的,forEachIndexed是迭代的好方法.

  2. 备选方案1:withIndexIterable类型定义的扩展可以在for-each中使用:

    val ints = arrayListOf(1, 2, 3, 4, 5)
    
    for ((i, e) in ints.withIndex()) {
        println("$i: $e")
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 选择2:扩展属性indices可用于Collection,Array等等,这让你迭代就像一个普通的for从C,Java的等知名循环:

    for(i in ints.indices){
         println("$i: ${ints[i]}")
    }
    
    Run Code Online (Sandbox Code Playgroud)