dongxi6897
dongxi6897
采纳率0%
2018-06-03 22:04

Golang-如何从矩阵中删除行?

已采纳

So I have this 2D slice, for example:

s := [][]int{
    {0, 1, 2, 3},
    {4, 5, 6, 7},
    {8, 9, 10, 11},
}

fmt.Println(s)

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

How can I remove a full row from this 2D slice, so that the result would look like this if I decide to remove the middle row:

[[0 1 2 3] [8 9 10 11]]
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongre6404 dongre6404 3年前

    The formula to delete row at index i is:

    s = append(s[:i], s[i+1:])
    

    Here's a working example:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        s := [][]int{
            {0, 1, 2, 3},
            {4, 5, 6, 7}, // This will be removed.
            {8, 9, 10, 11},
        }
    
        // Delete row at index 1 without modifying original slice by
        // appending to a new slice.
        s2 := append([][]int{}, append(s[:1], s[2:]...)...)
        fmt.Println(s2)
    
        // Delete row at index 1. Original slice is modified.
        s = append(s[:1], s[2:]...)
        fmt.Println(s)
    }
    

    Try it in the Go playground.

    I recommend you to read Go Slice Tricks. Some of the tricks can be applied to multidimensional slices as well.

    点赞 评论 复制链接分享
  • douan3182 douan3182 3年前

    You can try the following:

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

    You can try the working code in the Golang playground

    Another alternative way is to use the following:

    i := 1
    s = s[:i+copy(s[i:], s[i+1:])]
    

    Golang Playground

    点赞 评论 复制链接分享

为你推荐