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

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!