gpt4 book ai didi

dictionary - 检查一个值是否在列表中

转载 作者:IT王子 更新时间:2023-10-29 01:16:24 25 4
gpt4 key购买 nike

Go 有没有类似于 Python 的 in 关键字?我想检查一个值是否在列表中。

例如在 Python 中:

x = 'red'

if x in ['red', 'green', 'yellow', 'blue']:
print "found"
else:
print "not found"

在 Go 中,我想到了使用 set 习惯用法,但我认为这不是理想的,因为我必须指定一个我没有使用的 int 值。

x := "red"

valid := map[string]int{"red": 0, "green": 0,"yellow": 0, "blue": 0}

if _, ok := valid[x]; ok {
fmt.Println("found")
} else {
fmt.Println("not found")
}

我知道有一个 in 关键字可能与泛型有关。有没有办法使用 go generate 或其他东西来做到这一点?

最佳答案

您可以将 map[string]bool 用作集合。当测试并且键不在映射中时,返回 bool 的零值,即 false

所以用有效值作为键和 true 作为值填充映射。如果测试的键值在映射中,则其存储的 true 值将是结果。如果测试的键值不在映射中,则返回值类型的零值,即 false

使用它,测试变得如此简单:

valid := map[string]bool{"red": true, "green": true, "yellow": true, "blue": true}

if valid[x] {
fmt.Println("found")
} else {
fmt.Println("not found")
}

Go Playground 上试试(具有下面提到的变体)。

博文中提到了这一点:Go maps in action: Exploiting zero values

注意:

如果您有很多有效值,因为要存储在 map 中的所有值都是 true,使用 slice 列出有效值并使用 可能更紧凑for range 循环来初始化你的 map ,像这样:

for _, v := range []string{"red", "green", "yellow", "blue"} {
valid[v] = true
}

注释 #2:

如果您不想使用 for range 循环初始化,您仍然可以通过创建一个无类型的(或 bool 类型的)来稍微优化它-letter const:

const t = true
valid := map[string]bool{"red": t, "green": t, "yellow": t, "blue": t}

关于dictionary - 检查一个值是否在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30452433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com