在go语言中删除切片或数组中重复项的示例代码

2023-06-01 示例 组中 切片

如何删除切片中的重复项?


测试切片数据,例如,此切片有2个字符串重复项:

duplicate := []string{"Hello", "World", "GoodBye", "World", "We", "zongscan", "zongscan", "houtizong"}


代码示例:

用迭代切片并将非重复项复制到新切片

 package main

import (
"fmt"
)

func printslice(slice []string) {
fmt.Println("slice = ", slice)
//for i := range slice {
  // fmt.Println(i, slice[i])
//}
}

func stringInSlice(str string, list []string) bool {
for _, v := range list {
if v == str {
return true
}
}
return false
}

func main() {
duplicate := []string{"Hello", "World", "GoodBye", "World", "We", "zongscan", "zongscan", "houtizong"}

printslice(duplicate)

//需要从切片中删除重复数据
//这个想法是将数据复制到没有重复的新切片中

cleaned := []string{}

for _, value := range duplicate {

if !stringInSlice(value, cleaned) {
cleaned = append(cleaned, value)
}
}

printslice(cleaned)
}


输出 :

slice = [Hello World GoodBye World We zongscan zongscan houtizong]
slice = [Hello World GoodBye We zongscan houtizong]

相关文章

DTD示例5

2023-07-19 dtd 示例