2D数组不同的列大小

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

2d Array different column sizes

问题

假设我想创建一个类似于以下结构的二维数组:

/* [
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
] */

在Go语言中,你可以这样创建它:

matrix := [][]int{
    {2},
    {3, 4},
    {6, 5, 7},
    {4, 1, 8, 3},
}

如果你有一个列数相等的二维数组,例如:

/*   [4,1,8,1],
      [2,1,3,3],
      [7,1,4,3]
 */

你可以使用以下代码创建它:

matrix := make([][]int, 3)
for i := range matrix {
    matrix[i] = make([]int, 4)
}

希望这可以帮助到你!

英文:

Lets say I want to create a two dimensional array that looks like

/* [
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
] */

How do can I create it using go?

Typically if I have a 2d array with equal size columns like

 /*   [4,1,8,1],
      [2,1,3,3],
      [7,1,4,3]
 */

matrix := make([][]int, 4)
for i := range matrix {
	matrix[i] = make([]int, 3)
}

答案1

得分: 1

例如,

package main

import (
	"fmt"
)

func main() {
	matrix := make([][]int, 4)
	for i := range matrix {
		matrix[i] = make([]int, i+1)
	}
	fmt.Println(matrix)
}

输出:

[[0] [0 0] [0 0 0] [0 0 0 0]]

或者

package main

import (
	"fmt"
)

func main() {
	matrix := [][]int{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}
	fmt.Println(matrix)
}

输出:

[[2] [3 4] [6 5 7] [4 1 8 3]]
英文:

For example,

package main

import (
	"fmt"
)

func main() {
	matrix := make([][]int, 4)
	for i := range matrix {
		matrix[i] = make([]int, i+1)
	}
	fmt.Println(matrix)
}

Output:

[[0] [0 0] [0 0 0] [0 0 0 0]]

Or

package main

import (
	"fmt"
)

func main() {
	matrix := [][]int{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}}
	fmt.Println(matrix)
}

Output:

[[2] [3 4] [6 5 7] [4 1 8 3]]

答案2

得分: 1

你可以在matrix[i]上创建不同大小的切片:

matrix := make([][]int, 4)
for i := range matrix {
    matrix[i] = make([]int, i+1)
}
英文:

You can create slices of different sizes at matrix[i]:

matrix := make([][]int, 4)
for i := range matrix {
    matrix[i] = make([]int, i+1)
}

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

发表评论

匿名网友

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

确定