【发布时间】:2018-03-31 05:58:42
【问题描述】:
我可以在 Python 中编写:
for i, element in enumerate(my_list):
print i # the index, starting from 0
print element # the list-element
如何在 Kotlin 中编写此代码?
【问题讨论】:
我可以在 Python 中编写:
for i, element in enumerate(my_list):
print i # the index, starting from 0
print element # the list-element
如何在 Kotlin 中编写此代码?
【问题讨论】:
就像already 所说,forEachIndexed 是一种很好的迭代方式。
备选方案 1
为Iterable类型定义的扩展函数withIndex,可以在for-each中使用:
val ints = arrayListOf(1, 2, 3, 4, 5)
for ((i, e) in ints.withIndex()) {
println("$i: $e")
}
备选方案 2
扩展属性indices 可用于Collection、Array 等,让您可以像在C、Java 等已知的常见for 循环中一样进行迭代:
for(i in ints.indices){
println("$i: ${ints[i]}")
}
【讨论】:
标准库中有一个forEachIndexed函数:
myList.forEachIndexed { i, element ->
println(i)
println(element)
}
参见@s1m0nw1's answer,withIndex 也是一种非常好的迭代Iterable 的方法。
【讨论】: