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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化