go - 比较两个 slice

标签 go comparison slice

Go 中有没有办法比较两个 slice 并获取 slice X 中不在 slice Y 中的元素,反之亦然?

    X := []int{10, 12, 12, 12, 13}
    Y := []int{12, 14, 15}

func compare(X, Y []int)  

calling compare(X, Y)   
    result1 := []int{10, 12, 12, 13} // if you're looking for elements in slice X that are not in slice Y

calling compare(Y, X)
    result2 := []int{14, 15} // if you're looking for elements in slice Y that are not in slice X

最佳答案

如果顺序不重要,并且集合很大,你应该使用集合实现,并使用它的 diff 函数来比较它们。

集合不是标准库的一部分,但您可以使用这个库,例如,您可以使用它从 slice 中自动初始化集合。 https://github.com/deckarep/golang-set

类似这样的:

import (
    set "github.com/deckarep/golang-set"
    "fmt"
    )

func main() {
    //note that the set accepts []interface{}
    X := []interface{}{10, 12, 12, 12, 13}
    Y := []interface{}{12, 14, 15}

    Sx := set.NewSetFromSlice(X)
    Sy := set.NewSetFromSlice(Y)
    result1 := Sx.Difference(Sy)
    result2 := Sy.Difference(Sx)

    fmt.Println(result1)
    fmt.Println(result2)
}

关于go - 比较两个 slice ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23870102/

相关文章:

go - 远程调试 Go REST 端点

python - 使用 Python 读取具有给定结构定界的文本文件

http - 如何在请求中转义正斜杠以使 url-routers 将其计为 uri 参数的一部分?

转为二进制。读入数据片给出零结果

string - 我可以使用什么算法来确定两个文档中是否出现任意 n 个单词序列?

PHP 7.4 字符串比较

java、mysql比较和编辑值

python - 如何从字典键列表中提取特定项目

python - 在不使用 len() 的情况下切片到字符串的末尾

unit-testing - 如何模拟其中一种结构方法?