dqa35710 2015-07-07 08:58 采纳率: 0%
浏览 24
已采纳

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

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条回答 默认 最新

  • dongyong6428 2015-07-07 09:10
    关注

    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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)