如何在Golang中查找和删除切片中的元素?

问题描述:

我有几个数字: [1, -13, 9, 6, -21, 125]我想找到小于零的元素,然后删除它们。

它可以通过简单的方式来完成:只需遍历片,如果元素小于零->删除它。但计算成本很高,因为每一步都可能发生切片变化。

有没有什么优雅的方法?例如: numpy.where(array, condition) 以及numpy.delete?

Copy the surviving elements to the beginning of the slice, and reslice when done.

p := []int{1, -13, 9, 6, -21, 125}
j := 0

for _, n := range p {
    if n >= 0 {
        p[j] = n
        j++
    }
}
p = p[:j]

No memory is allocated, but the original slice is modified. If you cannot modify the original slice, then allocate and copy to a new slice:

p := []int{1, -13, 9, 6, -21, 125}
j := 0
q := make([]int, len(p))
for _, n := range p {
    if n >= 0 {
        q[j] = n
        j++
    }
}
q = q[:j] // q is copy with numbers >= 0

playground example