英文:
How to print multiple slices as one slice?
问题
在这段Golang代码中,我有一个名为developers
的变量,它等于两个切片。我希望它们等于一个切片,如所需结果所示。
虽然我可以通过将它们写成一个单独的切片来实现,例如{"第一个开发者", "第二个开发者"}
,但我想将它们分开写,并将它们打印为一个切片,但要将它们视为多个实体,如[[第一个开发者 第二个开发者]...]
。
给定结果
[[第一个开发者] [第二个开发者] [第一个项目 第二个项目] [第三个项目 第四个项目]]
所需结果
[[第一个开发者 第二个开发者] [第一个项目 第二个项目] [第三个项目 第四个项目]]
代码
package main
import "fmt"
func main() {
developers := [][]string{
{"第一个开发者"},
{"第二个开发者"},
}
var data [][]string
for i := 0; i < 2; i++ {
data = append(data, developers[i])
}
data = append(data, [][]string{
{"第一个项目", "第二个项目"},
{"第三个项目", "第四个项目"},
}...)
fmt.Println(data)
}
英文:
In this Golang code, I have a variable called developers
which is equal to two slices. I want them to be equal to one slice as shown in the required result.
Although I could do it by writing it in a single slice like this {"first developer", "second developer"},
but I want to write them separately and print them as one but to be considered as multiple entities like this [[first developer second developer]...]
Given result
[[first developer] [second developer] [first project second project] [third project forth project]]
Required result
[[first developer second developer] [first project second project] [third project forth project]]
Code
package main
import "fmt"
func main() {
developers := [][]string{
{"first developer"},
{"second developer"},
}
var data [][]string
for i := 0; i < 2; i++ {
data = append(data, developers[i])
}
data = append(data, [][]string{
{"first project", "second project"},
{"third project", "forth project"},
}...)
fmt.Println(data)
}
答案1
得分: 1
看起来你想要“展开”developers
的二维切片([][]string
)。为了做到这一点,可以遍历它并将其一维切片元素追加到一个一维切片([]string
)中。然后将这个一维切片作为最终data
二维切片的一个元素。
例如:
developers := [][]string{
{"第一个开发者"},
{"第二个开发者"},
}
var devs []string
for _, v := range developers {
devs = append(devs, v...)
}
data := [][]string{
devs,
{"第一个项目", "第二个项目"},
{"第三个项目", "第四个项目"},
}
fmt.Println(data)
这将输出(在Go Playground上尝试):
[[第一个开发者 第二个开发者] [第一个项目 第二个项目] [第三个项目 第四个项目]]
英文:
It looks first you want to "flatten" the developers
2D slice ([][]string
). To do that, range over it and append its 1D slice elements to a 1D slice ([]string
). Then use this 1D slice as an element of the final data
2D slice.
For example:
developers := [][]string{
{"first developer"},
{"second developer"},
}
var devs []string
for _, v := range developers {
devs = append(devs, v...)
}
data := [][]string{
devs,
{"first project", "second project"},
{"third project", "forth project"},
}
fmt.Println(data)
This will output (try it on the Go Playground):
[[first developer second developer] [first project second project] [third project forth project]]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论