假设我有两个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
如何以简单的方式检查?
答案 0 :(得分:2)
For example:
package main
import "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
}
Note that this solution does not exploit any potential performance optimizations (like assuming that the string arrays will be sorted in some way, or else) and hence has a runtime performance of O(m • n2), where:
Which is okay but not great.
答案 1 :(得分:0)
检查这两个地图之间交叉点的基数是否大于0。
请参阅set.go Intersect
中的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