gpt4 book ai didi

loops - 如何在 Groovy 的 eachWithIndex 方法中指定索引的起始值?

转载 作者:行者123 更新时间:2023-12-03 23:05:08 25 4
gpt4 key购买 nike

当使用 Groovy 的 eachWithIndex方法索引值从 0 开始,我需要它从 1 开始。我该怎么做?

最佳答案

索引总是从 0 开始

您的选择是:

1)向索引添加偏移量:

int offs = 1
list.eachWithIndex { it, idx ->
println "$it @ pos ${idx + offs}"
}

2) 使用除 eachWithIndex 以外的其他东西(即:用原始列表转置从 1 开始的整数列表,然后循环遍历)

3) 你也可以使用默认参数来破解这类东西... 如果我们通过 eachWithIndex一个带有 3 个参数的闭包( eachWithIndex 期望的两个参数和一个默认值为 index + 1 的第三个参数):
[ 'a', 'b', 'c' ].eachWithIndex { item, index, indexPlusOne = index + 1 ->
println "Element $item has position $indexPlusOne"
}

我们将给出输出:
Element a has position 1
Element b has position 2
Element c has position 3

关于loops - 如何在 Groovy 的 eachWithIndex 方法中指定索引的起始值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8821618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com