Collections 围棋中有套路吗?(类似于Python)
python中是否有类似于“Set”的Go集合 备选方案:Collections 围棋中有套路吗?(类似于Python),collections,set,go,Collections,Set,Go,python中是否有类似于“Set”的Go集合 备选方案: 有没有一种在围棋中实现集合的简单方法 是否有任何方法可以消除切片中的重复项 您可以使用映射[whatevertype]bool并将值设置为true。您可以将切片中的每个元素添加为映射键,然后使用范围仅获取唯一的元素 package main import "fmt" func main() { m := make(map[string]bool) s := make([]string, 0) s = appen
- 有没有一种在围棋中实现集合的简单方法
- 是否有任何方法可以消除切片中的重复项李>
映射[whatevertype]bool
并将值设置为true
。您可以将切片中的每个元素添加为映射键,然后使用范围
仅获取唯一的元素
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)
}
目前在golang中没有set实现。你需要自己做,或者找一个第三方库。这里还有一篇不错的博文:
我认为
map[T]bool
是最好的选择,但另一个选择是
映射[T]结构{}
:
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)
}
}
它不容易处理,但如果这是一个因素的话,它会占用更少的内存
对于您。我只想补充一点,您实际上可以使用任意类型作为值,因为您不关心它。但是使用
bool
始终设置为true有一个额外的好处,即可以通过索引来测试元素是否存在,因为当您索引一个键而它不存在时,它将返回值类型的零值,这对于布尔值来说是false。