douju9272 2015-12-05 08:04
浏览 132

GoLang:如何从2D切片中删除元素?

I've recently been messing around with Go and I wanted to see how it would be to delete an element from a two-dimensional slice.

For deleting an element from a one-dimensional slice, I can successfully use:

data = append(data[:i], data[i+1:]...)

However, with a two-dimensional slice, using:

data = append(data[i][:j], data[i][j+1:]...)

throws the error:

cannot use append(data[i][:j], data[i][j+1:]...) (type []string) as type [][]string in assignment

Would tackling this require a different approach?

  • 写回答

2条回答 默认 最新

  • dre93205 2015-12-05 09:19
    关注

    Here is one of the possible approaches <kbd>Go Playground</kbd>.

    b := [][]int{
        []int{1, 2, 3, 4},
        []int{5, 6, 7, 8},
        []int{9, 0, -1, -2},
        []int{-3, -4, -5, -6},
    }
    print2D(b)
    i, j := 2, 2
    
    
    tmp := append(b[i][:j], b[i][j+1:]...)
    c := append(b[:i], tmp)
    c = append(c, b[i+1:]...)
    print2D(c)
    

    Basically I am extracting the i-th row, remove the element from it append(b[i][:j], b[i][j+1:]...) and then put this row between the rows.

    If someone would tell how to append many elements, it would look even nicer.

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料