猿问

如何从 Go 中的切片中删除重复的字符串或整型

假设我有一个学生城市列表,它的大小可能是100或1000,我想过滤掉所有重复的城市。


我想要一个通用解决方案,可用于从任何切片中删除所有重复的字符串。


我是Go语言的新手,所以我试图通过循环并使用另一个循环函数检查元素是否存在来做到这一点。


学生城市列表(数据):


studentsCities := []string{"Mumbai", "Delhi", "Ahmedabad", "Mumbai", "Bangalore", "Delhi", "Kolkata", "Pune"}

我创建的函数,它正在做这项工作:


func contains(s []string, e string) bool {

    for _, a := range s {

        if a == e {

            return true

        }

    }

    return false

}


func removeDuplicates(strList []string) []string {

    list := []string{}

    for _, item := range strList {

        fmt.Println(item)

        if contains(list, item) == false {

            list = append(list, item)

        }

    }

    return list

}

我的解决方案测试


func main() {

    studentsCities := []string{"Mumbai", "Delhi", "Ahmedabad", "Mumbai", "Bangalore", "Delhi", "Kolkata", "Pune"}


    uniqueStudentsCities := removeDuplicates(studentsCities)

    

    fmt.Println(uniqueStudentsCities) // Expected output [Mumbai Delhi Ahmedabad Bangalore Kolkata Pune]

}

我认为我尝试的上述解决方案不是最佳解决方案。因此,我需要你们的帮助来建议从切片中删除重复项的最快方法?


我检查了StackOverflow,这个问题还没有被问到,所以我没有得到任何解决方案。


互换的青春
浏览 179回答 4
4回答

侃侃无极

我发现Burak和Fazlan的解决方案很有帮助。基于此,我实现了简单的函数,这些函数有助于使用通用方法从字符串,整数或任何其他类型的切片中删除或筛选重复数据。这是我的三个函数,第一个是泛型的,第二个是字符串,最后一个是切片的整数。您必须传递数据并返回所有唯一值作为结果。通用解决方案:=> Go v1.18func removeDuplicate[T string | int](sliceList []T) []T {    allKeys := make(map[T]bool)    list := []T{}    for _, item := range sliceList {        if _, value := allKeys[item]; !value {            allKeys[item] = true            list = append(list, item)        }    }    return list}从切片中删除重复字符串:func removeDuplicateStr(strSlice []string) []string {    allKeys := make(map[string]bool)    list := []string{}    for _, item := range strSlice {        if _, value := allKeys[item]; !value {            allKeys[item] = true            list = append(list, item)        }    }    return list}从切片中删除重复的整数:func removeDuplicateInt(intSlice []int) []int {    allKeys := make(map[int]bool)    list := []int{}    for _, item := range intSlice {        if _, value := allKeys[item]; !value {            allKeys[item] = true            list = append(list, item)        }    }    return list}您可以更新切片类型,它将筛选出所有类型切片的所有重复数据。以下是GoPlayground链接:https://go.dev/play/p/iyb97KcftMa

偶然的你

您可以使用地图进行就地替换:processed := map[string]struct{}{}w := 0for _, s := range cities {    if _, exists := processed[s]; !exists {        // If this city has not been seen yet, add it to the list        processed[s] = struct{}{}        cities[w] = s        w++    }}cities = cities[:w]

明月笑刀无情

但是,添加这个对我有用的答案确实需要/包括排序。func removeDuplicateStrings(s []string) []string {&nbsp; &nbsp; if len(s) < 1 {&nbsp; &nbsp; &nbsp; &nbsp; return s&nbsp; &nbsp; }&nbsp; &nbsp; sort.Strings(s)&nbsp; &nbsp; prev := 1&nbsp; &nbsp; for curr := 1; curr < len(s); curr++ {&nbsp; &nbsp; &nbsp; &nbsp; if s[curr-1] != s[curr] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s[prev] = s[curr]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prev++&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return s[:prev]}为了好玩,我尝试使用泛型!(仅限 Go 1.18+)type SliceType interface {&nbsp; &nbsp; ~string | ~int | ~float64 // add more *comparable* types as needed}func removeDuplicates[T SliceType](s []T) []T {&nbsp; &nbsp; if len(s) < 1 {&nbsp; &nbsp; &nbsp; &nbsp; return s&nbsp; &nbsp; }&nbsp; &nbsp; // sort&nbsp; &nbsp; sort.SliceStable(s, func(i, j int) bool {&nbsp; &nbsp; &nbsp; &nbsp; return s[i] < s[j]&nbsp; &nbsp; })&nbsp; &nbsp; prev := 1&nbsp; &nbsp; for curr := 1; curr < len(s); curr++ {&nbsp; &nbsp; &nbsp; &nbsp; if s[curr-1] != s[curr] {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; s[prev] = s[curr]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; prev++&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return s[:prev]}Go Playground Link with tests: https://go.dev/play/p/bw1PP1osJJQ

阿波罗的战车

简单易懂。func RemoveDuplicate(array []string) []string {&nbsp; &nbsp; m := make(map[string]string)&nbsp; &nbsp; for _, x := range array {&nbsp; &nbsp; &nbsp; &nbsp; m[x] = x&nbsp; &nbsp; }&nbsp; &nbsp; var ClearedArr []string&nbsp; &nbsp; for x, _ := range m {&nbsp; &nbsp; &nbsp; &nbsp; ClearedArr = append(ClearedArr, x)&nbsp; &nbsp; }&nbsp; &nbsp; return ClearedArr}
随时随地看视频慕课网APP

相关分类

Go
我要回答