猿问

如何在切片上迭代,一次 4 个项目

如何一次迭代 Go 切片 4 个项目。


可以说我有[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]


我想要一个 for 循环能够得到


[1,2,3,4] //First Iteration

[5,6,7,8] //Second Iteration

[9,10,11,12] //Third Iteration

[13,14,15,] // Fourth Iteration

我可以在 java 和 python 中做到这一点,但对于 golang 我真的不知道。


有只小跳蛙
浏览 123回答 2
2回答

慕姐4208626

例如,package mainimport "fmt"func main() {&nbsp; &nbsp; slice := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}&nbsp; &nbsp; for i := 0; i < len(slice); i += 4 {&nbsp; &nbsp; &nbsp; &nbsp; var section []int&nbsp; &nbsp; &nbsp; &nbsp; if i > len(slice)-4 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; section = slice[i:]&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; section = slice[i : i+4]&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(section)&nbsp; &nbsp; }}游乐场:https://play.golang.org/p/kf7_OJcP13t输出:[1 2 3 4][5 6 7 8][9 10 11 12][13 14 15]

Helenr

如何在 Go 中迭代切片,一次迭代 4 个项目。我想要一个 for 循环。在 Go 中,可读性至关重要。首先我们读取正常路径,然后读取异常/错误路径。我们写正常的路径。n := 4for i := 0; i < len(s); i += n {&nbsp; &nbsp; ss := s[i : i+n]&nbsp; &nbsp; fmt.Println(ss)}我们n始终使用步幅值。我们编写了一个小调整,不会干扰处理异常(切片末尾)的正常路径。if n > len(s)-i {&nbsp; &nbsp; n = len(s) - i}例如,package mainimport "fmt"func main() {&nbsp; &nbsp; s := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}&nbsp; &nbsp; n := 4&nbsp; &nbsp; for i := 0; i < len(s); i += n {&nbsp; &nbsp; &nbsp; &nbsp; if n > len(s)-i {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n = len(s) - i&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ss := s[i : i+n]&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println(ss)&nbsp; &nbsp; }}游乐场:https://play.golang.org/p/Vtpig2EeXB7输出:[1 2 3 4][5 6 7 8][9 10 11 12][13 14 15]
随时随地看视频慕课网APP

相关分类

Go
我要回答