英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论