简体   繁体   English

比较GO中的地图值

[英]Comparing the values of maps in GO

I have to compare the values (not keys) of two maps of type ' map[string]float64 '. 我必须比较两个类型为map[string]float64的映射的值(而不是键)。

The contents of the maps are : map1[ABCD:300 PQRS:400] and map2[ABCD:30 PQRS:40] No I do a check like if value(map1)/value(map2) > = 1 (like 300/30=10>1), then do something. 地图的内容为: map1[ABCD:300 PQRS:400]map2[ABCD:30 PQRS:40]不,我不会像value(map1)/ value(map2)> = 1(例如300/30)那样进行检查= 10> 1),然后执行一些操作。

How can I achieve this in GO ? 如何在GO中实现呢? TIA. TIA。

i tried something like this : 我尝试过这样的事情:

for key := range m2{
            for k := range m1{
                temp := m1[k] / m2[key]
                fmt.Println("temp*******", temp)
            }
        }

Playground working example 操场上的工作实例

Breaking down the main for loop: 分解主要的for循环:

for key, value1 := range m1 {
    if value2, ok := m2[key]; ok {
        fmt.Printf("%f / %f = %f\n", value1, value2, value1/value2)
        if value2 != 0 && value1/value2 > 1 {
            fmt.Println("Greater than 1!")
        } else {
            fmt.Println("Not greater than 1!")
        }
    }
}

First I use range to pull out both a value and a key for every entry in m1, since we need both. 首先,我使用range为m1中的每个条目提取值和键,因为我们需要两者。

Second, using the comma ok syntax of value2, ok := m2[key] , I'm both finding out what the associated value of the second map is for the given key, and also ensuring that that map entry exists when the surrounding if ... ; ok 其次,使用逗号OK语法value2, ok := m2[key] ,我都找到了什么第二张地图的相关值是给定的关键,也是确保当周围的那个地图项存在if ... ; ok if ... ; ok . if ... ; ok From your description of the problem, it isn't necessary to check every element of the second map, only those that share keys with the first. 根据问题的描述,不必检查第二个映射的每个元素,而只需检查与第一个共享密钥的元素。 It's important we make this check, since go doesn't throw errors when checking a map for a non-existent key, it just silently returns the zero-value of the variable--in this scenario that could mean dividing by zero later on. 我们进行此检查很重要,因为go在检查映射中不存在的键时不会抛出错误,它只是默默地返回变量的零值-在这种情况下,这可能意味着以后要除以零。

Third, well, just some formatted printlines to help see what's happening, the real juice is the very simple if value1/value2 > 1 statement. 第三,好吧,只有一些格式化的打印行可以帮助您了解正在发生的事情, if value1/value2 > 1语句是真正的汁液,则非常简单。 Note that I also added in my playground link some map entries that don't fulfill the requirement to help demonstrate that the behavior is correct. 请注意,我还在游乐场链接中添加了一些不符合要求的地图条目,以帮助证明行为正确。

The "go maps in action" blog article linked in the other answer is indeed a great source for working with maps in go. 在另一个答案中链接的“运行中的地图”博客文章的确是使用go中的地图的绝佳资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM