duanming0494 2015-02-24 15:17
浏览 120
已采纳

删除切片中的元素

I am complete newbie in Golang, I am trying to remove elements in one slice based on the elements in another slice. e.g.

input slice : urlList := []string{"test", "abc", "def", "ghi"}

elements to remove slice : remove := []string{"abc", "test"}

expected output slice : urlList := []string{"def", "ghi"}

This is what I tried.

func main() {

    urlList := []string{"test", "abc", "def", "ghi"}
    remove := []string{"abc", "test"}
loop:
    for i, url := range urlList {
        for _, rem := range remove {
            if url == rem {
                urlList = append(urlList[:i], urlList[i+1:]...)
                continue loop
            }
        }
    }
    for _, v := range urlList {
        fmt.Println(v)
    }
}

But it's not working as I expected. I don't know what I am missing.

  • 写回答

4条回答 默认 最新

  • doujiang5211 2015-02-24 15:21
    关注

    The problem is that when you remove an element from the original list, all subsequent elements are shifted. But the range loop doesn't know that you changed the underlying slice and will increment the index as usual, even though in this case it shouldn't because then you skip an element.

    And since the remove list contains 2 elements which are right next to each other in the original list, the second one ("abc" in this case) will not be checked and will not be removed.

    One possible solution is not to use range in the outer loop, and when you remove an element, you manually decrease the index i-- because continuing with the next iteration it will get auto-incremented:

    urlList := []string{"test", "abc", "def", "ghi"}
    remove := []string{"abc", "test"}
    
    loop:
    for i := 0; i < len(urlList); i++ {
        url := urlList[i]
        for _, rem := range remove {
            if url == rem {
                urlList = append(urlList[:i], urlList[i+1:]...)
                i-- // Important: decrease index
                continue loop
            }
        }
    }
    
    fmt.Println(urlList)
    

    Output:

    [def ghi]
    

    Note:

    Since the outer loop contains nothing after the inner loop, you can replace the label+continue with a simple break:

    urlList := []string{"test", "abc", "def", "ghi"}
    remove := []string{"abc", "test"}
    
    for i := 0; i < len(urlList); i++ {
        url := urlList[i]
        for _, rem := range remove {
            if url == rem {
                urlList = append(urlList[:i], urlList[i+1:]...)
                i-- // Important: decrease index
                break
            }
        }
    }
    
    fmt.Println(urlList)
    

    Try it on Go Playground.

    Alternative

    An alternative to this would be for the outer loop to go downward, so no need to manually decrease (or increase) the index variable because the shifted elements are not affected (already processed due to the downward direction).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)