例如在Python中:
x ='红色' 如果x在['red','green','yellow','blue'中]: printfound else: printnot 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)}我知道中的关键字可能与泛型有关。有没有办法做到这一点,使用生成或什么?
解决方案您可以使用字符串] bool 作为一个集合。当测试和一个键不在地图中时,返回 bool 的零值,即 false 。
因此,请使用有效的值作为键和 true 作为值来填充地图。如果测试的键值在映射中,则其结果存储为 true 值。如果测试的键值不在映射中,则返回值类型的零值,即 false 。
使用这个,测试变得这么简单: valid:= map [string] bool {red:true ,green:true,yellow:true,blue:true} if valid [x] { fmt.Println(found)}其他{ fmt.Println(找不到)}试试它在 Go Playground (带有下面提到的变体)。
这在博客文章中提到: 开始使用地图:利用零值 b / p>
如果您有许多有效值,因为所有要存储在地图中的值都是 true ,它可能是使用切片列出有效值并使用范围循环来初始化您的贴图更加简洁,如下所示:
for _,v:= range [] string {red,green,yellow,blue} { valid [v] = true注意2:
如果您不想使用来进行范围循环初始化,您仍然可以通过创建一个无类型(或 bool -typed)单字母 const :
const t = true valid:= map [string] bool {red:t,green:t,yellow:t,blue: t}
Does Go have something similar to Python's in keyword? I want to check if a value is in a list.
For example in Python:
x = 'red' if x in ['red', 'green', 'yellow', 'blue']: print "found" else: print "not found"In Go I've come up with using the set idiom but I don't think it's ideal as I have to specify a int value that I'm not using.
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") }I understand having an in keyword is probably related to generics. Is there a way to do this using go generate or something?
解决方案You can use a map[string]bool as a set. When testing and a key is not in the map, the zero value for bool is returned which is false.
So fill the map with the valid values as keys and true as value. If a tested key-value is in the map, its stored true value will be the result. If a tested key-value is not in the map, the zero value for the value type is returned which is false.
Using this, the test becomes this simple:
valid := map[string]bool{"red": true, "green": true, "yellow": true, "blue": true} if valid[x] { fmt.Println("found") } else { fmt.Println("not found") }Try it on the Go Playground (with the variants mentioned below).
This is mentioned in the blog post: Go maps in action: Exploiting zero values
Note:
If you have many valid values, since all the values to be stored in the map are true, it may be more compact to use a slice to list the valid values and use a for range loop to initialize your map, something like this:
for _, v := range []string{"red", "green", "yellow", "blue"} { valid[v] = true }Note #2:
If you don't want to go with the for range loop initialization, you can still optimize it a little by creating an untyped (or bool-typed) one-letter const:
const t = true valid := map[string]bool{"red": t, "green": t, "yellow": t, "blue": t}
更多推荐
检查一个值是否在列表中
发布评论