我试图弄清楚如何从循环内的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)
正如您在评论中指出的那样,您没有特别要求循环....如果您乐意修改原始列表,您可以使用removeAll:
// Remove all negative numbers
list = [1, 2, -4, 8]
list.removeAll { it < 0 }
Run Code Online (Sandbox Code Playgroud)
我认为你可以这样做:
\n\nlist - 2;\nRun Code Online (Sandbox Code Playgroud)\n\n或者...
\n\nlist.remove(2)\nRun Code Online (Sandbox Code Playgroud)\n\n不需要循环。
\n\n如果您想使用循环,我想您可以考虑使用迭代器来实际删除该项目。
\n\nimport 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\nRun Code Online (Sandbox Code Playgroud)\n\n但我不明白你为什么要这样做。
\n| 归档时间: |
|
| 查看次数: |
40631 次 |
| 最近记录: |