【问题标题】:Golang - How to remove a row from a matrix?Golang - 如何从矩阵中删除一行?
【发布时间】:2018-06-03 22:04:05
【问题描述】:

所以我有这个 2D 切片,例如:

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]]

如何从这个 2D 切片中删除一整行,以便在我决定删除中间行时结果如下所示:

[[0 1 2 3] [8 9 10 11]]

【问题讨论】:

标签: go 2d slice


【解决方案1】:

删除索引i处的行的公式是:

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

这是一个工作示例:

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.

我建议你阅读Go Slice Tricks。一些技巧也可以应用于多维切片。

【讨论】:

    【解决方案2】:

    您可以尝试以下方法:

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

    您可以尝试Golang playground中的工作代码

    另一种替代方法是使用以下方法:

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

    Golang Playground

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 2011-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多