Kotlin是否有“枚举"字样?像Python一样的功能? [英] Does Kotlin have an "enumerate" function like Python?
本文介绍了Kotlin是否有“枚举"字样?像Python一样的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Python中,我可以写:
In Python I can write:
for i, element in enumerate(my_list):
print i # the index, starting from 0
print element # the list-element
我怎么用Kotlin来写这个?
How can I write this in Kotlin?
推荐答案
There is a forEachIndexed
function in the standard library:
myList.forEachIndexed { i, element ->
println(i)
println(element)
}
也请参见 @ s1m0nw1的答案,withIndex
也是迭代Iterable
的一种非常不错的方法
See @s1m0nw1's answer as well, withIndex
is also a really nice way to iterate through an Iterable
.
这篇关于Kotlin是否有“枚举"字样?像Python一样的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文