Groovy在循环之后没有返回列表的列表
我正在学习Groovy,我试图返回一个列表的列表,但是当我在for循环中执行counter()
函数时,它会自动返回给我第一次迭代,继续其余的话。Groovy在循环之后没有返回列表的列表
我发现问题出在for循环的counter()
,它看起来像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)
避免全球范围: 前缀与隐式类型def
(实际上Object
)或适当的显式类型(例如int
或Integer
)的i
变量声明做出的范围本地环路。否则,将这些变量放置在脚本的绑定中(作为单个文件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, 1,2,3,4,5],[0,1,2,3,4,5],[0,1,2,3,4],[0,1,2,3,4,5,6, 8,9]]
Groovy的方式
为了给你一些额外的提示,我重新实现使用一些很酷的功能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]]
**“Groovy Way”**将使用'collect'而不是在每个'block'中使用变量列表 –
@tim_yates:感谢您的建议 –
能否请您给一些建议吗?如果答案不能解决您的问题,您能提供一些失败的测试用例吗? –