我可以在 Python 中编写:
for i, element in enumerate(my_list):
print(i) # the index, starting from 0
print(element) # the list-element
如何在 Kotlin 中编写此代码?
最佳答案
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
等,让您像普通的 for
C、Java 等已知的循环:
for(i in ints.indices){
println("$i: ${ints[i]}")
}
关于list - Kotlin 有像 Python 一样的 "enumerate"函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46825787/