dsfs5420 2018-01-06 00:33 采纳率: 100%
浏览 1712
已采纳

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

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

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

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

  • 写回答

1条回答 默认 最新

  • dqpu4988 2018-01-06 00:40
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?