duanjiao8007 2016-07-18 11:40 采纳率: 100%
浏览 26
已采纳

go-检查一张地图的钥匙是否在另一张地图中[重复]

This question already has an answer here:

I have one dictionary

a = {1:11, 2:22}

I want to check if key in b is present in a or not

b = {3:33, 1:11}

How can I do this in Go language?

I have done it like this:

a:= make(map[string][]string)
a["1"] = append(a["1"], "11")
a["1"] = append(a["1"], "22")

I have a dict b as:

b:= make(map[string]string)
b["1"] = "11"

How can I check this? Essentially, I want to check if key 1 from b is present in a or not.

</div>
  • 写回答

1条回答 默认 最新

  • dongyun3897 2016-07-18 12:10
    关注

    You can either use the go idiomatic way to check for a key presence:

    if _, ok:= b[key]; ok
    

    Example:

    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)
            }
        }   
    }
    

    Playground Example 1

    Or you can check if the key value from the first map corresponds to the value from the second map:

    for key, val := range a {
        if val == b[key] {          
            fmt.Printf("%s
    ", key)
        }
    }
    

    Playground Example 2

    But the first one is the idiomatic way.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动