Does Kotlin have an “enumerate” function like Python?

后端 未结 2 1590
心在旅途
心在旅途 2020-12-17 08:41

In Python I can write:

for i, element in enumerate(my_list):
    print i          # the index, starting from 0
    print element    # the list-element
         


        
2条回答
  •  自闭症患者
    2020-12-17 08:55

    Iterations in Kotlin: Some Alternatives

    Like already said, forEachIndexed is a good way to iterate.

    Alternative 1

    The extension function withIndex, defined for Iterable types, can be used in for-each:

    val ints = arrayListOf(1, 2, 3, 4, 5)
    
    for ((i, e) in ints.withIndex()) {
        println("$i: $e")
    }
    

    Alternative 2

    The extension property indices is available for Collection, Array etc., which let's you iterate like in a common for loop as known from C, Java etc:

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

提交回复
热议问题