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 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?