go - checking if key of one map present in another
本问题已经有最佳答案,请猛点这里访问。
我有一本字典
1 | a = {1:11, 2:22} |
我想检查EDOCX1[0]中的密钥是否存在于EDOCX1[1]中
1 | b = {3:33, 1:11} |
我怎样才能用围棋语言做到这一点?
我是这样做的:
1 2 3 | a:= make(map[string][]string) a["1"] = append(a["1"],"11") a["1"] = append(a["1"],"22") |
我的口述是:
1 2 | b:= make(map[string]string) b["1"] ="11" |
我怎么检查这个?本质上,我想检查来自
您可以使用Go惯用方法检查密钥是否存在:
1 | if _, ok:= b[key]; ok |
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | var ( a = map[string]int{ "alpha": 34,"bravo": 56,"charlie": 23, "delta": 87,"echo": 56,"foxtrot": 12,"golf": 34,"hotel": 16, "indio": 87,"juliet": 65,"kilo": 43,"lima": 98} b = map[string]int{ "alpha": 34,"one": 56,"charlie": 23, "insdio": 87,"julietta": 65,"kilo": 43,"lima": 98} ) func main() { for key, _ := range a { if _, ok:= b[key]; ok { fmt.Printf("%s ", key) } } } |
操场示例1
或者,您可以检查第一个映射的键值是否与第二个映射的值对应:
1 2 3 4 5 6 | for key, val := range a { if val == b[key] { fmt.Printf("%s ", key) } } |
操场示例2
但第一个是惯用的方法。