在Python中我可以写:
for i, element in enumerate(my_list):
print i # the index, starting from 0
print element # the list-element
我怎么能在Kotlin写这个?
答案 0 :(得分:21)
标准库中有forEachIndexed
函数:
myList.forEachIndexed { i, element ->
println(i)
println(element)
}
同样请参阅@s1m0nw1's answer,withIndex
也是一种非常好的方法来迭代Iterable
。
答案 1 :(得分:18)
与BasicDBObjectBuilder一样,forEachIndexed
是一种很好的迭代方式。
备选方案1:为withIndex
类型定义的扩展程序Iterable
可以在for
中使用 - 每个:
val ints = arrayListOf(1, 2, 3, 4, 5)
for ((i, e) in ints.withIndex()) {
println("$i: $e")
}
备选方案2:扩展属性indices
可用于Collection
,Array
等,这样您就可以在公共for
循环中进行迭代C,Java等:
for(i in ints.indices){
println("$i: ${ints[i]}")
}