更新时间:2023-12-05 15:44:40
如果您想使用 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]