英文:
How to return the unique elements of large data structures in go?
问题
我是你的中文翻译助手,以下是翻译好的内容:
我是Go语言的新手,在代码中找到Go语言中的唯一元素方面遇到了困难。
var arr [10]string
arr[0]="table"
arr[1]="chair"
arr[2]="table"
arr[3]="table"
arr[4]="chair"
arr[5]="bench"
arr[6]="table,chair"
arr[7]="bench,chair"
arr[8]="chair,table,bench"
arr[9]="car"
输出应该是:
table
chair
bench
car
我真的卡在这里了。如何从上述数组中获取唯一元素。数组中还包含逗号分隔的值,但我只需要打印唯一的元素。
请有人帮助我。
提前感谢。
英文:
I am new to Go language and troubling in the code to find the unique elements in the go.
var arr [10]string
arr[0]="table"
arr[1]="chair"
arr[2]="table"
arr[3]="table"
arr[4]="chair"
arr[5]="bench"
arr[6]="table,chair"
arr[7]="bench,chair"
arr[8]="chair,table,bench"
arr[9]="car"
The output should be like:
table
chair
bench
car
I am really stuck on this. how to get the unique elements from the above array.
The array contains comma seperated values also but i need to print only the unique elements.
Pls someone help me on this.
Thanks for advance.
答案1
得分: 4
思路:使用map[string]bool
来收集唯一元素,使用strings.Split
将逗号分隔的单词列表拆分为字符串。
示例:http://play.golang.org/p/sBopFGrzbX
package main
import (
"fmt"
"strings"
)
func main() {
arr := [...]string{
"table",
"chair",
"table",
"table",
"chair",
"bench",
"table,chair",
"bench,chair",
"chair,table,bench",
"car",
}
m := make(map[string]bool)
for _, e := range arr {
for _, w := range strings.Split(e, ",") {
m[w] = true
}
}
for k, _ := range m {
fmt.Println(k)
}
}
代码解释:该代码使用map
来存储唯一的元素,通过遍历数组中的每个元素,使用strings.Split
函数将逗号分隔的单词拆分为字符串,并将每个单词作为map
的键,值设为true
。最后,遍历map
并打印每个键。
英文:
Idea: use map[string]bool
to collect unique elements, use strings.Split
to split comma-separated list of words into strings.
Example: http://play.golang.org/p/sBopFGrzbX
package main
import (
"fmt"
"strings"
)
func main() {
arr := [...]string{
"table",
"chair",
"table",
"table",
"chair",
"bench",
"table,chair",
"bench,chair",
"chair,table,bench",
"car",
}
m := make(map[string]bool)
for _, e := range arr {
for _, w := range strings.Split(e, ",") {
m[w] = true
}
}
for k, _ := range m {
fmt.Println(k)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论