How to find the dimensions of a (2,3 or if possible an n)dimensional slice in golang and verify if its a matrix?

huangapple go评论68阅读模式
英文:

How to find the dimensions of a (2,3 or if possible an n)dimensional slice in golang and verify if its a matrix?

问题

例如:[][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}} 的维度是 [2,4]

如果将其传递给一个函数,那么最有效的方法是如何找到这里的维度?

谢谢。

英文:

For example : [][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}} has dimensions [2,4].

If this is passed to a function then what is the most efficient way to find the dimension here?

Thanks

答案1

得分: 2

外部维度只是len(x),其中x是您传递给函数的切片的切片(例如[][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}})。
然而,内部维度不能保证相等,所以您需要遍历每个元素并检查它们的len

如果您保证x的每个元素具有相同数量的元素,只需找到len(x[0]),如果len(x) > 0

英文:

The outer dimension is just len(x) where x is the slice of slices you pass to the function (your example [][]float64{{11, 5, 14, 1}, {11, 5, 14, 1}}).
However, the inner dimensions are not guaranteed to be equal so you will have to go through each element and check what len they have.

If you have the guarantee than each element of x has the same number of elements, just find len(x[0]) if len(x) > 0.

答案2

得分: 1

Go只提供一维数组和切片。可以通过使用数组的数组来模拟N维数组,这与你正在做的事情接近——你有一个一维切片,其中包含两个一维切片。

这是有问题的,因为切片的长度是不确定的。所以你可能会得到长度差异很大的切片:

[][]float64{
    {1, 2, 3, 4},
    {5, 6, 7, 8, 9, 10},
}

如果你使用实际的数组,这会更简单,因为数组有固定的长度:

[2][4]float64

你可以将其扩展到任意多的维度:

[2][4][8]float64提供了三个维度,分别为2、4和8。

然后,你可以通过在任何元素上使用内置的len()函数来确定每个维度的容量:

foo := [2][4][7]float64{}
x := len(foo)       // x == 2
y := len(foo[0])    // y == 4
z := len(foo[0][0]) // z == 8
英文:

Go only provides 1-dimensional arrays and slices. N-dimensional arrays can be emulated by using arrays of arrays, which is close to what what you're doing--you have a 1-dimensional slice, which contains 2 1-dimensional slices.

This is problematic, because slices are not of a defined length. So you could end up with slices of wildly different lengths:

[][]float64{
    {1, 2, 3, 4},
    {5, 6, 7, 8, 9, 10},
}

If you use actual arrays, this is simpler, because arrays have a fixed length:

[2][4]float64

You can extend this to as many dimensions as you want:

[2][4][8]float64 provides three dimensions, with respective depths of 2, 4, and 8.

Then you can tell the capacity of each dimension by using the built-in len() function on any of the elements:

foo := [2][4][7]float64{}
x := len(foo)       // x == 2
y := len(foo[0])    // y == 4
z := len(foo[0][0]) // z == 8

huangapple
  • 本文由 发表于 2017年8月21日 02:40:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/45785639.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定