【问题标题】:Does Kotlin have an "enumerate" function like Python?Kotlin 是否有像 Python 一样的“枚举”函数?
【发布时间】: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 中编写此代码?

【问题讨论】:

    标签: list kotlin enumerate


    【解决方案1】:

    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 等,让您可以像在C、Java 等已知的常见for 循环中一样进行迭代:

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

    【讨论】:

    • 两者的表现有什么要强调的吗?
    【解决方案2】:

    标准库中有一个forEachIndexed函数:

    myList.forEachIndexed { i, element ->
        println(i)
        println(element)
    }
    

    参见@s1m0nw1's answerwithIndex 也是一种非常好的迭代Iterable 的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-23
      • 2016-05-15
      • 2015-06-16
      相关资源
      最近更新 更多