Go语言程序计算两个切片的差异
切片也可以称为动态数组,因为它的值是动态的,而普通数组是静态的。这使得切片更高效、更快。它们是通过引用传递而不是通过值传递。在这里,我们将学习如何找到两个切片或两个动态数组之间的差异。
语法
func make ([] type, size, capacity)
Go 语言中的 make 函数用于创建数组/映射,它接受要创建的变量的类型、大小和容量作为参数。
func append(slice, element_1, element_2…, element_N) []T
append 函数用于向数组切片添加值。它接受多个参数。第一个参数是要添加值的数组,后面跟着要添加的值。然后,该函数返回包含所有值的最终数组切片。
算法
步骤 1 − 创建一个 package main 并声明 fmt(格式化包)包在程序中,其中 main 生成可执行代码,而 fmt 帮助格式化输入和输出。
步骤 2 − 创建一个函数 main,并在该函数中创建一个名为 myslice1 的切片 1,并在控制台上打印它。
步骤 3 − 同样,在控制台上创建一个名为 myslice2 的切片 2,并在控制台上打印它。
步骤 4 − 使用 make 函数创建一个空切片以追加两个切片之间差异的值。
步骤 5 − 运行一个循环,直到切片 1 的范围,并将 found 变量最初设置为 false。
步骤 6 − 在嵌套形式中运行另一个循环,并检查第一个切片中的元素是否等于第二个切片中的元素。
步骤 7 − 如果为真,则将 found 变量设置为 true 并中断循环,但如果为假,则继续循环。
步骤 8 − 循环终止时,检查 found 是否为 false,将切片 1 的值追加到切片差异中并移动到下一个迭代,但如果没有相同的值,则意味着差异为 0。
步骤 9 − 使用 fmt.Println() 函数在控制台上打印切片,其中 ln 表示换行。
示例 1
在这个例子中,我们将看到如何使用嵌套 for 循环计算两个切片之间的差异。这里的差异是指存在于切片 1 中但在切片 2 中不存在的值。
package main
import (
"fmt"
)
func main() {
myslice1 := []int{10, 20, 30, 40, 50} //create slice1
fmt.Println("The elements of slice1 are:", myslice1)
myslice2 := []int{30, 40, 50, 60, 70} //create slice2
fmt.Println("The elements of slice2 are:", myslice2)
difference := make([]int, 0) //create difference slice to store the difference of two slices
// Iterate over slice1
for _, val1 := range myslice1 { //nested for loop to check if two values are equal
found := false
// Iterate over slice2
for _, val2 := range myslice2 {
if val1 == val2 {
found = true
break
}
}
if !found {
difference = append(difference, val1)
}
}
fmt.Println("The difference of two slices is:", difference)
}
输出
The elements of slice1 are: [10 20 30 40 50] The elements of slice2 are: [30 40 50 60 70] The difference of two slices is: [10 20]
示例 2
在这个例子中,我们将使用 Go 语言中的映射计算两个切片之间的差异。元素以一种方式进行检查,如果它存在于第二个映射中,则不会将其追加到差异切片中。
package main
import (
"fmt"
)
func main() {
myslice1 := []int{10, 20, 30, 40, 50} //create slice1
fmt.Println("The elements of slice1 are:",myslice1)
myslice2 := []int{30, 40, 50, 60, 70} //create slice2
fmt.Println("The elements of slice2 are:",myslice2)
difference := make([]int, 0)
map1 := make(map[int]bool)
map2 := make(map[int]bool)
for _, val := range myslice1 {
map1[val] = true
}
for _, val := range myslice2 {
map2[val] = true
}
for key := range map1 {
if _, ok := map2[key]; !ok {
difference = append(difference, key) //if element not present in map2 append elements in difference slice
}
}
fmt.Println("The difference between two slices is:")
fmt.Println("Difference:", difference) //print difference
}
输出
The elements of slice1 are: [10 20 30 40 50] The elements of slice2 are: [30 40 50 60 70] The difference between two slices is: Difference: [10 20]
结论
我们使用两个示例执行了查找两个切片之间差异的程序。在第一个示例中,我们使用了嵌套 for 循环,在第二个示例中,我们使用了 Go 语言中的映射。
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP