gpt4 book ai didi

go - 如何删除golang上 slice 之间的重复元素

转载 作者:数据小太阳 更新时间:2023-10-29 03:47:14 24 4
gpt4 key购买 nike

例子:

a_array := {"1","2","3","4,"}
b_array := {"3","4"}

期望的结果:

"1","2"

假设a_array元素肯定有b_array元素。

最佳答案

如果您需要严格比较一个 slice 和另一个 slice ,您可以按照以下方式做一些事情

func diff(a []string, b []string) []string {
// Turn b into a map
var m map[string]bool
m = make(map[string]bool, len(b))
for _, s := range b {
m[s] = false
}
// Append values from the longest slice that don't exist in the map
var diff []string
for _, s := range a {
if _, ok := m[s]; !ok {
diff = append(diff, s)
continue
}
m[s] = true
}
// Sort the resulting slice
sort.Strings(diff)
return diff
}

Go Playground


或者,如果你想从两个 slice 中获取所有不存在于它们中的值,你可以这样做

func diff(a []string, b []string) []string {
var shortest, longest *[]string
if len(a) < len(b) {
shortest = &a
longest = &b
} else {
shortest = &b
longest = &a
}
// Turn the shortest slice into a map
var m map[string]bool
m = make(map[string]bool, len(*shortest))
for _, s := range *shortest {
m[s] = false
}
// Append values from the longest slice that don't exist in the map
var diff []string
for _, s := range *longest {
if _, ok := m[s]; !ok {
diff = append(diff, s)
continue
}
m[s] = true
}
// Append values from map that were not in the longest slice
for s, ok := range m {
if ok {
continue
}
diff = append(diff, s)
}
// Sort the resulting slice
sort.Strings(diff)
return diff
}

然后

fmt.Println(diff(a_array, b_array))

给你

[1 2]

Go playground

关于go - 如何删除golang上 slice 之间的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53194031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com