03.两个切片内容相减的几种方法
2023年1月6日约 512 字大约 2 分钟
03.两个切片内容相减的几种方法
问题
已知: var a []string = []string{"11", "33", "22", "44"} var b []string = []string{"11", "22"} var b []string 预期: c = []string{"11", "22"}
1,运维的思路
方法一
package main
import "fmt"
func main() {
var (
weightInstanceList []string = []string{"11", "22", "33", "44"}
RelateInstance []string = []string{"11", "22"}
a []string // 期望:22,33,44
)
fmt.Println(weightInstanceList, RelateInstance)
// 循环老的
for _, instance := range weightInstanceList {
// 传入待删除IP切片 老的IP 进行判断 是否相等 相等表示待删除 反之加入更新jenkinsFile列表
isOk := IsContain(RelateInstance, instance)
if !isOk {
a = append(a, instance)
}
}
fmt.Println("最后结果:", a) // a=["11","11","11"]
}
func IsContain(items []string, item string) bool {
for _, eachItem := range items {
if eachItem == item {
return true
}
}
return false
}
方法二
package main
import "fmt"
func main() {
var (
weightInstanceList []string = []string{"11", "33", "22", "44"}
RelateInstance []string = []string{"11", "22"}
)
fmt.Println(weightInstanceList[1:])
for _, instance := range weightInstanceList {
for _, item := range RelateInstance {
if instance == item {
weightInstanceList = RemoveParam(weightInstanceList, instance)
}
}
}
fmt.Println("最后结果:", weightInstanceList) // a=["11","11","11"]
}
func RemoveParam(sli []string, n string) []string {
for i := 0; i < len(sli); i++ {
if sli[i] == n {
if i == 0 {
sli = sli[1:]
} else if i == len(sli)-1 {
sli = sli[:i]
} else {
sli = append(sli[:i], sli[i+1:]...)
}
i-- // 如果索引i被去掉后,原来索引i+1的会移动到索引i
}
}
return sli
}
2开发的思路
方法一
package main
import "fmt"
func main() {
var (
weightInstanceList []string = []string{"11", "33", "22", "44"}
RelateInstance []string = []string{"11", "22"}
)
fmt.Println(diff(weightInstanceList, RelateInstance))
}
func diff(a, b []string) []string {
var (
r []string
m = make(map[string]struct{}, len(a))
)
for _, v := range b {
m[v] = struct{}{}
}
for _, v := range a {
if _, ok := m[v]; !ok {
r = append(r, v)
}
}
return r
}
方法二
package main
import "fmt"
func main() {
var (
weightInstanceList []string = []string{"11", "33", "22", "44"}
RelateInstance []string = []string{"11", "22"}
)
fmt.Println(diff(weightInstanceList, RelateInstance))
}
func diff(a, b []string) []string {
var (
r []string
m = make(map[string]struct{}, len(a))
)
for _, v := range a {
m[v] = struct{}{}
}
for _, v := range b {
delete(m, v)
}
for k, _ := range m {
r = append(r, k)
}
return r
}
可以看出,运维处理该问题时思路会困在当前类型中予以实现,不如开发对数据结构以及特性掌握的牢固,运用起来也就不够灵活了。
Powered by Waline v2.9.1