使用go中的范围选择2D切片的2D子切片 [英] selecting 2D sub-slice of a 2D-slice using ranges in go
问题描述
选择切片的2D子切片时,我得到了令人惊讶的结果.考虑下面的二维int数组
a:= [] [] int {{0,1,2,3},{1,2,3,4},{2,3,4,5},{3,4,5,6},}
要使用我要使用的范围来选择左上3x3 2D切片
b:= a [0:2] [0:2]
我希望结果是
[[0 1 2] [1 2 3] [2 3 4]]
但是第二个索引范围似乎没有任何作用,而是返回以下内容:
[[0 1 2 3] [1 2 3 4] [2 3 4 5]]
我想念什么?您是否可以简单地不选择尺寸> 1的子切片?
您无法一步一步完成自己想做的事情.切片和数组不是二维的,它们只是组成一个多维对象而构成.参见二维数组的内存表示如何 >
因此,使用slice表达式,您仅得到一个将容纳完整"行的子集的slice,其类型将相同: [] [] int
.如果再次对其进行切片,则只需再次对行的切片进行切片.
还请注意,切片表达式中的较高索引是互斥的,因此 a [0:2]
仅具有2行,因此应使用 a [0:3]
或简单地 a [:3]
.
要获得所需的内容,您必须像这样分别对行进行切片:
b:= a [0:3]对于i:=范围b {b [i] = b [i] [0:3]}fmt.Println(b)
这将输出(在游乐场上尝试):
[[0 1 2] [1 2 3] [2 3 4]]
或更短:
b:= a [:3]对于i,bi:=范围b {b [i] = bi [:3]}
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 ?
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]
}
这篇关于使用go中的范围选择2D切片的2D子切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!