我正在学习Groovy而且我正在尝试返回一个列表列表但是当我在counter()
函数中执行for循环时,它会自动返回给我第一次迭代并且不会继续其余的单词。
我发现问题出现在counter()
的for循环中,看起来Groovy在循环中共享i
变量。来自Python的每个for循环都拥有自己的变量i
。在Groovy中有这样的东西吗?
lista = ["apple","banana","orange","melon","watermelon"]
def copaa(a_list_of_things){
lista_to_return = []
for (i = 0; i < a_list_of_things.size(); i++) {
lis = counter(a_list_of_things[i])
lista_to_return.add(lis)
}
return lista_to_return
}
def counter(word){
list_of_times = []
//return "bla"
for (i = 0; i < word.length(); i++) {
list_of_times.add(i)
}
return list_of_times
}
ls = copaa(lista)
println(ls)
答案 0 :(得分:1)
避免全球范围:
使用隐式类型i
(实际为def
)或适当的显式类型(例如Object
或int
)为Integer
变量声明添加前缀,以使范围成为本地循环。否则,这些变量将被放置在脚本的绑定中(作为单个i
)(实际上它被视为全局变量)。
修改代码的相关行,如下所示:
// with def...
for (def i = 0; i < a_list_of_things.size(); i++) {
// ...
for (def i = 0; i < word.length(); i++) {
// ...OR with an explicit type (e.g. int) the scope is limited
// to the for loop as expected
for (int i = 0; i < a_list_of_things.size(); i++) {
// ...
for (int i = 0; i < word.length(); i++) {
<强>输出强>
[[0,1,2,3,4],[0,1,2,3,4,5],[0,1,2,3,4,5],[0,1,2] ,3,4],[0,1,2,3,4,5,6,7,8,9]]
<小时/> Groovy Way
为了给你一些额外的提示,我使用groovy
提供的一些很酷的功能(collect,closure,numeric ranges)重新实现了算法:
wordList = ["apple","watermelon"]
// collect process each word (the implicit variable it) and returns a new list
// each field of the new list is a range from 0 till it.size() (not included)
outList = wordList.collect { (0 ..< it.size()).toArray() }
assert outList == [[0, 1, 2, 3, 4], [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]