list - Kotlin 有像 Python 一样的 "enumerate"函数吗?

标签 list kotlin enumerate

我可以在 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 扩展属性可用于 CollectionArray 等,让您像普通的 for C、Java 等已知的循环:

for(i in ints.indices){
     println("$i: ${ints[i]}")
}

关于list - Kotlin 有像 Python 一样的 "enumerate"函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46825787/

相关文章:

gradle - 哪个jvmTarget用于kotlin项目?

linux - 在 Linux 中是否有枚举分配的堆 block 的标准方法?

python - 刽子手 : replacing an * with player input guess

c++ - 使用其指针从列表中删除项目

kotlin - 房间用构造函数生成ID

python - 如何在Python中从列表中选择一些项目?

kotlin - Ktor sse 客户端断开连接

python - 附加元音位置 Python

python - Google App Engine 上的 ListProperty 与 StringListProperty

c# List 不添加项目