如何删除Golang上切片之间的重复元素

时间:2018-11-07 16:44:48

标签: go

作为标题, 如何删除golang上切片之间的重复元素

例如。

a_array := {"1","2","3","4,"}
b_array := {"3","4"}

希望结果

"1","2"

假设,a_array元素肯定具有b_array元素。 请告诉我该怎么做。 谢谢!

1 个答案:

答案 0 :(得分:-1)

如果您需要严格地将一个切片与另一个切片进行比较,则可以按照以下步骤进行操作

func diff(a []string, b []string) []string {
    // Turn b into a map
    var m map[string]bool
    m = make(map[string]bool, len(b))
    for _, s := range b {
        m[s] = false
    }
    // Append values from the longest slice that don't exist in the map
    var diff []string
    for _, s := range a {
        if _, ok := m[s]; !ok {
            diff = append(diff, s)
            continue
        }
        m[s] = true
    }
    // Sort the resulting slice
    sort.Strings(diff)
    return diff
}

Go Playground


或者,如果您希望从两个切片中都不存在的两个切片中获取所有值,则可以

func diff(a []string, b []string) []string {
    var shortest, longest *[]string
    if len(a) < len(b) {
        shortest = &a
        longest = &b
    } else {
        shortest = &b
        longest = &a
    }
    // Turn the shortest slice into a map
    var m map[string]bool
    m = make(map[string]bool, len(*shortest))
    for _, s := range *shortest {
        m[s] = false
    }
    // Append values from the longest slice that don't exist in the map
    var diff []string
    for _, s := range *longest {
        if _, ok := m[s]; !ok {
            diff = append(diff, s)
            continue
        }
        m[s] = true
    }
    // Append values from map that were not in the longest slice
    for s, ok := range m {
        if ok {
            continue
        }
        diff = append(diff, s)
    }
    // Sort the resulting slice
    sort.Strings(diff)
    return diff
}

然后

fmt.Println(diff(a_array, b_array))

会给你

[1 2]

Go playground