在Go语言中是否存在集合(类似于Python中的集合)?

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

Do Sets exist in Go? (like in Python)

问题

有没有类似于Python中的'Set'的Go集合?

替代方案:

  • 在Go中有没有实现集合的简单方法?
  • 有没有办法在切片中消除重复项?
英文:

Is there any Go collection similar to 'Set's in python?

alternatives:

  • Is there an easy way of implementing Sets in Go?
  • Is there any method to eliminate duplicates in a slice?

答案1

得分: 15

你可以使用map[任意类型]bool,并将值设置为true。你可以将切片中的每个元素作为map的键,然后使用range来获取唯一的元素。

package main
import "fmt"
func main() {
    m := make(map[string]bool)
    s := make([]string, 0)
    s = append(s, "foo")
    s = append(s, "foo")
    s = append(s, "foo")
    s = append(s, "bar")
    s = append(s, "bar")
    for _, r := range s {
        m[r] = true
    }
    s = make([]string, 0)
    for k, _ := range m {
        s = append(s, k)
    }
    fmt.Printf("%v\n", s)
}
英文:

You could just have a map[whatevertype]bool and set the value to true. You could add every element in a slice as a map key, then use a range to get only the unique ones back out.

package main
import "fmt"
func main() {
    m := make(map[string]bool)
    s := make([]string, 0)
    s = append(s, "foo")
    s = append(s, "foo")
    s = append(s, "foo")
    s = append(s, "bar")
    s = append(s, "bar")
    for _, r := range s {
        m[r] = true
    }
    s = make([]string, 0)
    for k, _ := range m {
        s = append(s, k)
    }
    fmt.Printf("%v\n", s)
}

答案2

得分: 2

我认为map[T]bool是最好的选择,但另一个选项是map[T]struct{}

package main

func main() {
   { // 示例 1
      s := make(map[string]struct{})
      s["north"] = struct{}{}
      s["south"] = struct{}{}
      _, ok := s["north"]
      println(ok)
   }
   { // 示例 2
      s := map[string]struct{}{
         "north": {}, "south": {},
      }
      _, ok := s["north"]
      println(ok)
   }
}

虽然它不太容易使用,但如果内存是一个因素,它占用的内存较少。

英文:

I think the map[T]bool is the best option, but another option is
map[T]struct{}:

package main

func main() {
   { // example 1
      s := make(map[string]struct{})
      s["north"] = struct{}{}
      s["south"] = struct{}{}
      _, ok := s["north"]
      println(ok)
   }
   { // example 2
      s := map[string]struct{}{
         "north": {}, "south": {},
      }
      _, ok := s["north"]
      println(ok)
   }
}

it's not as easy to work with, but it takes up less memory if that is a factor for you.

答案3

得分: 1

目前在golang中没有集合的实现。你需要自己实现或者使用第三方库。这里还有一篇不错的博客文章:https://www.openmymind.net/2011/7/15/Learning-Go-By-Benchmarking-Set-Implementation/

英文:

There is no set implementation in golang at this point. You'll need to do it yourself or get a third party lib. Also here is a nice blog post:

https://www.openmymind.net/2011/7/15/Learning-Go-By-Benchmarking-Set-Implementation/

huangapple
  • 本文由 发表于 2011年8月12日 23:15:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/7042250.html
匿名

发表评论

匿名网友

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

确定