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条)

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面