【问题标题】:Ways to compare two golang lists to check all elements are unique比较两个golang列表以检查所有元素的方法是唯一的
【发布时间】:2020-06-20 00:20:12
【问题描述】:

问题如标题所述。给定两个已知类型的列表,而您只是想确保两个列表没有使用任何相同的元素,那么如何在 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-ish。

【问题讨论】:

  • 这是在大多数情况下和语言(代码行数!= 效率)中最有效的方法。 Go 不提倡“创意”或“古怪”。如果您想检查具有基本类型的较大集合中的成员资格,请使用地图。
  • 我建议使用地图然后你可以附加地图

标签: list go compare unique


【解决方案1】:

我同意@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。

【讨论】:

    猜你喜欢
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 1970-01-01
    • 2015-10-18
    • 2019-12-07
    相关资源
    最近更新 更多