问题如标题中所述。给定两个已知类型的列表,并且您只想确保两个列表都没有使用任何相同的元素,那么如何在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中,是否有替代方法或更“正确”的方式进行比较?
额外注意:您还想听听做这件事的任何酷/创意/古怪的方式。
最佳答案
我同意@JimB。您的示例是比较 slice 的有效方法。参见map vs switch performance in go。比较 byte slice 而不是字符串也是有效的。参见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。
关于list - 比较两个golang列表以检查所有元素的方法是唯一的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60578040/