dongxi6897 2018-06-03 22:04 采纳率: 0%
浏览 78
已采纳

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 2018-06-03 22:28
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程