go语言中在两个切片、数组中查找共性(交集)的示例代码
下面介绍两个切片或数组中查找共性交集示例的方法
方法1:
//切片交集1
a := []string{"Hello", "No", "Zongscan"}
b := []string{"Hello", "Yes", "Zongscan"}
d := []string{}
for i := range a {
if a[i] == b[i] {
d = append(d, a[i])
}
}
fmt.Println("共性交集1: ", d)
方法2:
// 切片交集2
a_one := []string{"Hello", "No", "Zongscan"}
b_two := []string{"Hello", "Yes", "Zongscan"}
d2 := []string{}
for _, v1 := range a_one {
isAdd := false
for _, v2 := range b_two {
if v1 == v2 {
isAdd = true
}
}
if isAdd {
d2 = append(d2, v1)
}
}
fmt.Println("共性交集2: ", d2)
完整测试代码:
package controllers
import (
"fmt"
)
// TestController is a test control
type TestController struct {
//beego.Controller
BaseController
}
func (c *TestController) Aaa() {
//两个切片或数组中查找共性交集示例
// 切片交集ces1
a := []string{"Hello", "No", "Zongscan"}
b := []string{"Hello", "Yes", "Zongscan"}
d := []string{}
for i := range a {
if a[i] == b[i] {
d = append(d, a[i])
}
}
fmt.Println("共性交集1: ", d)
// 切片交集ces2
a_one := []string{"Hello", "No", "Zongscan"}
b_two := []string{"Hello", "Yes", "Zongscan"}
d2 := []string{}
for _, v1 := range a_one {
isAdd := false
for _, v2 := range b_two {
if v1 == v2 {
isAdd = true
}
}
if isAdd {
d2 = append(d2, v1)
}
}
fmt.Println("共性交集2: ", d2)
}
效果图:
相关文章