如何检查地图是否可以在 golang 中部分匹配另一个地图

假设,我有两个 map[string]([]string)


 MAP1 := map[string]([]string) {

    "User" : []string{"11", "33"},

    "Type" : []string{"A"},

    }



MAP2 := map[string]([]string) {

    "User" : []string{"11", "17"},

    "Type" : []string{"B"},

    }

在这里,部分MAP1匹配MAP2。


User = 11 is in both map

我怎样才能以简单的方式检查这个?


慕村225694
浏览 209回答 2
2回答

繁星点点滴滴

对于例如:package mainimport "fmt"func Max(x, y int) int {    if x > y {        return x    }    return y}func Intersect(as, bs []string) []string {    i := make([]string, 0, Max(len(as), len(bs)))    for _, a := range as {        for _, b := range bs {            if a == b {                i = append(i, a)            }        }    }    return i}func main() {    MAP1 := map[string][]string{        "User": []string{"11", "33"},        "Type": []string{"A"},    }    MAP2 := map[string][]string{        "User": []string{"11", "17"},        "Type": []string{"B"},    }    MAP3 := make(map[string][]string)    for k, _ := range MAP1 {        MAP3[k] = Intersect(MAP1[k], MAP2[k])    }    fmt.Println(MAP3) // MAP3 contains commonalities between MAP1 and MAP2}请注意,此解决方案没有利用任何潜在的性能优化(例如假设字符串数组将以某种方式排序,或者其他方式),因此具有 O(m • n 2 )的运行时性能,其中:m 是映射中的键数(假设两个映射相同)n 是每个字符串切片中的元素数(假设两个对应的映射条目都相同)这是好的,但不是很好。

月关宝盒

您检查这两个地图之间的交集的基数是否大于 0。参见例如set.goIntersect in deckarep/golang-set。// Returns a new set containing only the elements// that exist only in both sets.//// Note that the argument to Intersect// must be of the same type as the receiver// of the method. Otherwise, Intersect will// panic.Intersect(other Set) Set
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go