如何在列表中循环并删除groovy中的项目?

ScA*_*er2 17 groovy

我试图弄清楚如何从循环内的groovy中删除列表中的项目.

static main(args) {
   def list1 = [1, 2, 3, 4]
   for(num in list1){
   if(num == 2)
      list1.remove(num)
   }
   println(list1)
}
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 19

list = [1, 2, 3, 4]
newList = list.findAll { it != 2 }
Run Code Online (Sandbox Code Playgroud)

应该给你除2之外的所有

当然你可能有理由要求循环?


ata*_*lor 15

如果要删除索引为 2 的项目,则可以执行此操作

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]
Run Code Online (Sandbox Code Playgroud)

如果要删除值为 2 的(第一个)项,则可以执行此操作

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]
Run Code Online (Sandbox Code Playgroud)


veg*_*4me 7

正如您在评论中指出的那样,您没有特别要求循环....如果您乐意修改原始列表,您可以使用removeAll:

// Remove all negative numbers
list = [1, 2, -4, 8]
list.removeAll { it < 0 }
Run Code Online (Sandbox Code Playgroud)


Jon*_*Jon 5

我认为你可以这样做:

\n\n
list - 2;\n
Run Code Online (Sandbox Code Playgroud)\n\n

或者...

\n\n
list.remove(2)\n
Run Code Online (Sandbox Code Playgroud)\n\n

不需要循环。

\n\n

如果您想使用循环,我想您可以考虑使用迭代器来实际删除该项目。

\n\n
import java.util.Iterator;\n\nstatic main(args) {   def list1 = [1, 2, 3, 4]\n   Iterator i = list1.iterator();\n   while (i.hasNext()) {\n      n = i.next();\n      if (n == 2) i.remove();\n   }\n   println(list1)\n}\xe2\x80\x8b\n
Run Code Online (Sandbox Code Playgroud)\n\n

但我不明白你为什么要这样做。

\n