Go語言程式:從切片中移除子集
切片類似於陣列,唯一的區別是陣列是元素的固定序列,而切片中的陣列元素是動態的。這使得切片在各種應用中更有效率和更快。在切片中,元素是透過引用而不是值傳遞的。在本文中,我們將學習使用 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 來儲存子集的值。
廣告