如何循环浏览列表并删除groovy中的项目? [英] How do I loop through a list and remove an item in groovy?
本文介绍了如何循环浏览列表并删除groovy中的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
static 我试图找出如何从循环中的groovy列表中删除一个项目。 main(args){
def list1 = [1,2,3,4]
for(num in list1){
if(num == 2)
list1.remove (num)
}
println(list1)
}
解决方案
如果您想使用 index 2删除项目,您可以执行
list = [1,2,3,4]
list.remove(2)
断言列表== [1,2,4]
/ /或循环
list = [1,2,3,4]
i = list.iterator()
2.times {
i.next()
}
i.remove()
断言列表== [1,2,4]
如果您想要使用 value 2删除(第一个)项目,您可以执行
list = [1,2,3,4]
list.remove(list.indexOf(2))
断言列表== [1,3,4]
//或带循环
list = [1,2,3,4]
i = list.iterator()
while(i.hasNext()){
if(i.next()== 2){
i.remove()
break
}
}
断言列表== [1,3,4 ]
I'm trying to figure out how to remove an item from a list in groovy from within a loop.
static main(args) {
def list1 = [1, 2, 3, 4]
for(num in list1){
if(num == 2)
list1.remove(num)
}
println(list1)
}
解决方案
If you want to remove the item with index 2, you can do
list = [1,2,3,4]
list.remove(2)
assert list == [1,2,4]
// or with a loop
list = [1,2,3,4]
i = list.iterator()
2.times {
i.next()
}
i.remove()
assert list == [1,2,4]
If you want to remove the (first) item with value 2, you can do
list = [1,2,3,4]
list.remove(list.indexOf(2))
assert list == [1,3,4]
// or with a loop
list = [1,2,3,4]
i = list.iterator()
while (i.hasNext()) {
if (i.next() == 2) {
i.remove()
break
}
}
assert list == [1,3,4]
这篇关于如何循环浏览列表并删除groovy中的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文