登录
首页 >  Golang >  Go问答

比较两个 golang 列表以检查所有元素是否唯一的方法

来源:stackoverflow

时间:2024-04-01 10:06:35 181浏览 收藏

目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《比较两个 golang 列表以检查所有元素是否唯一的方法》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~

问题内容

问题如标题所示。给定两个已知类型的列表,并且您只想确保两个列表不使用任何相同的元素,如何在 golang 中有效地检查这一点。

对于 golang 来说还是相对较新的。在python中,我可能会做这样的事情:

a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 1]

def check_lists_are_unique(list_one, list_two):
    return not bool(len(set(list_one) & set(list_two)))

print(check_lists_are_unique(a, b)) # returns true
print(check_lists_are_unique(a, c)) # returns false
print(check_lists_are_unique(b, c)) # returns true

我自己在 golang 中的第一次尝试是:

a := []int{1, 2, 3}
b := []int{4, 5, 6}
c := []int{7, 8, 1}

checkUnique := func(listOne, listTwo []int) bool {
    for _, i := range listOne {
        for _, j := range listTwo {
            if i == j {
                return false
            }
        }
    }
    return true
}
fmt.Println(checkUnique(a, b)) // returns true
fmt.Println(checkUnique(a, c)) // returns false
fmt.Println(checkUnique(b, c)) // returns true

https://play.golang.org/p/vubnv97mywb

想知道这是否真的是在 golang 中进行比较的最有效方法?在 golang 中是否有替代方案或更“正确”的方式进行比较?

额外说明:还想听听任何酷/创意/古怪的、独特的 golang 方式。


解决方案


我同意@jimb。您的示例是比较切片的有效方法。请参阅 map vs switch performance in go。比较字节片段而不是字符串也很有效。请参阅 Better to compare slices or bytes?。对于整数来说也可能如此。请参阅下面的代码和 https://play.golang.org/p/w59ctLV9C9S

a := []byte{1, 2, 3}
  b := []byte{4, 5, 6}
  c := []byte{7, 8, 1}

  checkUnique := func(listOne, listTwo []byte) bool {
     for _, i := range listOne {
        for _, j := range listTwo {
           if i == j {
              return false
           }
        }
     }
     return true
  }
  fmt.Println(checkUnique(a, b)) // returns true
  fmt.Println(checkUnique(a, c)) // returns false
  fmt.Println(checkUnique(b, c)) // returns true

它可能不适用于您的问题,但 bytes.equal 对于比较两个 []byte 是有效的。请参阅 Checking the equality of two slices

到这里,我们也就讲完了《比较两个 golang 列表以检查所有元素是否唯一的方法》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>