drutcs7210 2018-11-07 16:44
浏览 724

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

As a title, how to delete duplicate elements between slices on golang

ex.

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

hope of result

"1","2"

With the assumption, a_array elements definitely has b_array elements. Please tell me how to do it. Thank you!

  • 写回答

1条回答 默认 最新

  • duanban4769 2018-11-07 19:27
    关注

    If you need to strictly compare one slice against the other you may do something along the lines of

    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


    Alternatively if you want to get all values from both slices that are not present in both of them you can do

    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
    }
    

    Then

    fmt.Println(diff(a_array, b_array))
    

    will give you

    [1 2]
    

    Go playground

    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b