Golang 从切片中删除一个子集

Golang 从切片中删除一个子集

切片类似于数组,唯一的区别是数组是固定的元素序列,而切片中的数组元素是动态的。这使得切片在各种应用中更高效和更快。在切片中,元素是通过引用而不是值传递的。在本文中,我们将学习使用Go语言编程从切片中删除一个子集的不同技术。

语法

func append(slice, element_1, element_2…, element_N) []T

append函数用于向数组切片中添加值。它接受多个参数。第一个参数是要添加值的数组,其后是要添加的值。该函数然后返回包含所有值的最终数组切片。

步骤

  • 步骤1: - 创建一个main包并声明fmt(格式化包)包。

  • 步骤2: - 在main函数中创建一个切片,并向该切片添加值。

  • 步骤3: - 创建切片的子集并调用内部函数。

  • 步骤4: - 创建一个输出切片,并对切片进行迭代。

  • 步骤5: - 打印输出。

示例1

在这个示例中,我们将看到如何使用嵌套的for循环从切片中删除子集。

package main
import "fmt"

func main() {
   slice := []int{10, 20, 30, 40, 50, 60} //create slice
   fmt.Println("The elements of slice are:", slice)
   subset := []int{30, 40, 50, 60} //create subset
   fmt.Println("The elements of subset which are to be removed are:", subset)
   slice = removesubset(slice, subset) // Call the removesubset function
   fmt.Println("The slice after removing elements subset from it are:")
   fmt.Println(slice)
}

// removesubset function
func removesubset(slice, subset []int) []int {
   for _, val := range subset {
      for i, element := range slice {
         if val == element {
            slice = append(slice[:i], slice[i+1:]...) //remove subset using append function
            break
         }
      }
   }
   return slice //return slice to the function after subsets are removed
}

输出

The elements of slice are: [10 20 30 40 50 60]
The elements of subset which are to be removed are: [30 40 50 60]
The slice after removing elements subset from it are:
[10 20]

示例2

在这个示例中,我们将使用map来存储使用make函数创建的子集的元素。make函数是Go语言的内置函数。

package main
import "fmt"

func main() {
   slice := []int{10, 20, 30, 40, 50, 60} //create slice
   fmt.Println("The elements of slice are:", slice)
   subset := []int{30, 40, 50, 60} //create subset
   fmt.Println("The elements of subset are:", subset)
   slice = removesubset(slice, subset)
   fmt.Println("The slice after removal of elements is:")
   fmt.Println(slice)
}
func removesubset(slice, subset []int) []int {
   subsetmap := make(map[int]bool) //create subsetmap using make function
   for _, element := range subset {
      subsetmap[element] = true
   }
   var output []int
   for _, val := range slice {
      if !subsetmap[val] {
         output = append(output, val)
      }
   }
   return output //return output slice without subsets
}

输出

The elements of slice are: [10 20 30 40 50 60]
The elements of subset are: [30 40 50 60]
The slice after removal of elements is:
[10 20]

结论

我们通过两个示例来执行从切片中删除子集的程序。在第一个示例中,我们使用了嵌套的for循环,而在第二个示例中,我们使用map来存储子集的值。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程