如何在Go语言中返回大型数据结构的唯一元素?

huangapple go评论92阅读模式
英文:

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)
	}
}

huangapple
  • 本文由 发表于 2015年7月7日 16:58:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/31264096.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定