arrays - Groovy,如何使用索引迭代列表

标签 arrays list groovy loops

有了 Groovy 中所有的速记方式,就必须有一种更简单的方法来迭代列表,同时访问迭代索引。

for(i in 0 .. list.size()-1) {
   println list.get(i)
}

基本 for 循环中是否没有隐式索引?

for( item in list){
    println item       
    println index
}

最佳答案

您可以使用eachWithIndex :

list.eachWithIndex { item, index ->
    println item
    println index
}

对于 Groovy 2.4 及更高版本,您还可以使用 indexed()方法。这可以很方便地使用 collect 等方法访问索引:

def result = list.indexed().collect { index, item ->
    "$index: $item"
}
println result

关于arrays - Groovy,如何使用索引迭代列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9522897/

相关文章:

c - 打印 C 中 int 数组的所有递减组合

c++ - 动态分配的 C 风格字符串的字符数超过给定长度?

具有刚性变量的数组

javascript - 当我的数组中只有 1 个对象时,控制台显示 4 个对象的信息

Java List - 如何获取多维列表的列值?

python - 在列表中查找包含最大数字的字符串

list - scala如何访问列表中元组中的元素

jenkins - Groovy 中的闭包不捕获外部变量

groovy - 管道到groovy脚本输入

grails - 在grails中将新项插入 “hasMany”对象时对其执行操作