【问题标题】:GoLang: How to delete an element from a 2D slice?GoLang:如何从 2D 切片中删除元素?
【发布时间】:2016-03-10 05:36:38
【问题描述】:

我最近一直在玩 Go,我想看看如何从二维切片中删除一个元素。

对于从一维切片中删除元素,我可以成功使用:

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

但是,对于二维切片,使用:

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

抛出错误:

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

解决这个问题需要不同的方法吗?

【问题讨论】:

    标签: arrays multidimensional-array go append slice


    【解决方案1】:

    Go 中的 2D 切片只不过是切片的切片。所以如果你想从这个 2D 切片中移除一个元素,实际上你仍然只需要从一个切片中移除一个元素(它是另一个切片的元素)。

    没有更多的参与。您唯一需要注意的是,当您从行切片中删除一个元素时,结果将只是“外部”切片的行(一个元素)的“新”值,而不是 2D 切片本身.因此,您必须将结果分配给外部切片的一个元素,即您刚刚删除其元素的行:

    // Remove element at the ith row and jth column:
    s[i] = append(s[i][:j], s[i][j+1:]...)
    

    请注意,如果我们将s[i] 替换为a,这与简单的“从切片中删除”相同(不足为奇,因为s[i] 表示我们要删除其jth 元素的“行切片” ):

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

    查看这个完整的例子:

    s := [][]int{
        {0, 1, 2, 3},
        {4, 5, 6, 7},
        {8, 9, 10, 11},
    }
    
    fmt.Println(s)
    
    // Delete element s[1][2] (which is 6)
    i, j := 1, 2
    s[i] = append(s[i][:j], s[i][j+1:]...)
    
    fmt.Println(s)
    

    输出(在Go Playground 上试试):

    [[0 1 2 3] [4 5 6 7] [8 9 10 11]]
    [[0 1 2 3] [4 5 7] [8 9 10 11]]
    

    【讨论】:

      【解决方案2】:

      这是一种可能的方法Go Playground

      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)
      

      基本上我正在提取i-th 行,从中删除元素append(b[i][:j], b[i][j+1:]...),然后将此行放在行之间。

      如果有人会告诉如何附加许多元素,它看起来会更好。

      【讨论】:

        猜你喜欢
        • 2016-09-16
        • 1970-01-01
        • 2018-06-15
        • 1970-01-01
        • 2019-10-17
        • 1970-01-01
        • 2014-11-28
        • 2019-02-05
        相关资源
        最近更新 更多