如何在Golang中找到两个切片的交集结果

huangapple go评论71阅读模式
英文:

How to finding result of intercept of two slices in golang

问题

有两个字符串切片,我想在Golang中找到这两个切片的交集结果,并且希望找到最佳解决方案,而不是遍历每个切片。

first_slice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E0","84-18-3A-2F-05-E8"} 
second_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8","F8-E7-1E-54-AE-08"}

输出:
result_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8"}

我已经尝试了以下方法,但对于大数据集来说并不是最佳方法:

var result_slice *[]string

for _, i := range first_slice {
    for _, x := range second_slice {
        if i == x {
            &result_slice.append(i)
        }
    }
}

如果能给我一个更好的解决方案,我将不胜感激。

英文:

There is two slices in string type.I want to finding intercept result in set from the two slices in golang.I want to find the best solution rather than iterating each slice.

first_slice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E0","84-18-3A-2F-05-E8" } 
second_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8","F8-E7-1E-54-AE-08"}


Output:
    result_slice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8"}

I have use following approaches but it is not best approaches for large data set.

var result_slice *[]string

for _, i := range first_slice {
    for _, x := range second_slice {
        if i == x {
            &result_slice.append(i)
        }
    }
}

Appreciate if give me good solution that.

答案1

得分: 2

第一部分:

firstSlice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30",
	"84-18-3A-2F-05-E0", "84-18-3A-2F-05-E8"}
secondSlice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8",
	"F8-E7-1E-54-AE-08"}

resultSlice := []string{}
checkMap := map[string]struct{}{}

for _, addr := range firstSlice {
	checkMap[addr] = struct{}{}
}
for _, addr := range secondSlice {
	if _, ok := checkMap[addr]; ok {
		resultSlice = append(resultSlice, addr)
	}
}

fmt.Println(resultSlice)

输出结果是你想要的。

空结构在内存中不占用空间。

此外,在Go语言中,始终使用驼峰命名法。

英文:
firstSlice := []string{"F8-E7-1E-14-AE-00", "F8-E7-1E-14-D0-30",
	"84-18-3A-2F-05-E0", "84-18-3A-2F-05-E8"}
secondSlice := []string{"F8-E7-1E-14-D0-30", "84-18-3A-2F-05-E8",
	"F8-E7-1E-54-AE-08"}

resultSlice := []string{}
checkMap := map[string]struct{}{}

for _, addr := range firstSlice {
	checkMap[addr] = struct{}{}
}
for _, addr := range secondSlice {
	if _, ok := checkMap[addr]; ok {
		resultSlice = append(resultSlice, addr)
	}
}

fmt.Println(resultSlice)

The output is what you want.

An empty struct takes no space in monery

What's more, always use camel in golang.

huangapple
  • 本文由 发表于 2016年11月23日 22:14:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/40766824.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定