douyan7916 2019-02-03 21:33
浏览 37
已采纳

使用go中的范围选择2D切片的2D子切片

I'm getting a surprising result when selecting a 2D sub-slice of a slice. Consider the following 2D int array

a := [][]int{
    {0, 1, 2, 3},
    {1, 2, 3, 4},
    {2, 3, 4, 5},
    {3, 4, 5, 6},
}

To select the top left 3x3 2D slice using ranges I would use

b := a[0:2][0:2]

I would expect the result to be

[[0 1 2] [1 2 3] [2 3 4]]

however the second index range doesn't seem to have any effect, and returns the following instead:

[[0 1 2 3] [1 2 3 4] [2 3 4 5]]

What am I missing? Can you simply not select a sub-slice like this where the dimension > 1 ?

  • 写回答

1条回答 默认 最新

  • ds20021205 2019-02-03 22:14
    关注

    You can't do what you want in a single step. Slices and arrays are not 2-dimensional, they are just composed to form a multi-dimensional object. See How is two dimensional array's memory representation

    So with a slice expression, you just get a slice that will hold a subset of the "full" rows, and its type will be the same: [][]int. If you slice it again, you just slicing the slice of rows again.

    Also note that the higher index in a slice expression is exclusive, so a[0:2] will only have 2 rows, so you should use a[0:3] or simply a[:3] instead.

    To get what you want, you have to slice the rows individually like this:

    b := a[0:3]
    for i := range b {
        b[i] = b[i][0:3]
    }
    fmt.Println(b)
    

    This will output (try it on the Go Playground):

    [[0 1 2] [1 2 3] [2 3 4]]
    

    Or shorter:

    b := a[:3]
    for i, bi := range b {
        b[i] = bi[:3]
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿