Does Kotlin have an “enumerate” function like Python?

后端 未结 2 1591
心在旅途
心在旅途 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 09:06

    There is a forEachIndexed function in the standard library:

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

    See @s1m0nw1's answer as well, withIndex is also a really nice way to iterate through an Iterable.

提交回复
热议问题