猿问

如何反转阵列|在高朗中切片而不使用 for 语句

我正在寻找一种在Golang中反转的方法,而无需使用任何语句。我找不到任何解决方案。我发现这篇文章 如何反转一个切片 go?,但每个解决方案都是使用语句。我知道处理这个问题的最佳方法是使用,但我正在寻找其他解决方案,而不必[][]string|intforforfor

 list := [][]int{
            {2,3,4}, 
            {6,8,1},
        }

结果是这样的:[[2 3 4] [6 8 1]].

但我需要这样的东西:[[6 8 1] [2 3 4]].

如果不使用该语句,我该怎么办?有什么想法吗?for


慕侠2389804
浏览 63回答 2
2回答

饮歌长啸

如果不使用 for 语句,我该怎么办?有什么想法吗?递归调用package mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; list := [][]int{&nbsp; &nbsp; &nbsp; &nbsp; {2, 3, 4},&nbsp; &nbsp; &nbsp; &nbsp; {6, 8, 1},&nbsp; &nbsp; }&nbsp; &nbsp; reverse(list)&nbsp; &nbsp; fmt.Println(list)}func reverse(d [][]int) {&nbsp; &nbsp; j := len(d) - 1&nbsp; &nbsp; i := 0&nbsp; &nbsp; var h func()&nbsp; &nbsp; h = func() {&nbsp; &nbsp; &nbsp; &nbsp; if i<j {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; d[i], d[j] = d[j], d[i]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i, j = i+1, j-1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; h()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; h()}转到语句package mainimport (&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; list := [][]int{&nbsp; &nbsp; &nbsp; &nbsp; {2, 3, 4},&nbsp; &nbsp; &nbsp; &nbsp; {6, 8, 1},&nbsp; &nbsp; }&nbsp; &nbsp; reverse(list)&nbsp; &nbsp; fmt.Println(list)}func reverse(d [][]int) {&nbsp; &nbsp; j := len(d) - 1&nbsp; &nbsp; i := 0START:&nbsp; &nbsp; if i < j {&nbsp; &nbsp; &nbsp; &nbsp; d[i], d[j] = d[j], d[i]&nbsp; &nbsp; &nbsp; &nbsp; i, j = i+1, j-1&nbsp; &nbsp; &nbsp; &nbsp; goto START&nbsp; &nbsp; }}

慕姐4208626

在这里使用循环 - 是最简单的解决方案。forPS:您可以尝试使用像这样的硬编码解决方案:list2&nbsp;:=&nbsp;[][]int{list[1],&nbsp;list[0]}但它是黑客而不是解决方案,所以最好使用基于循环的漂亮简洁的程序化解决方案。for
随时随地看视频慕课网APP

相关分类

Go
我要回答