dongqianzhan8325 2017-02-18 15:58
浏览 691
已采纳

GoLang:检查切片1中的项目是否包含在切片2中。如果包含,请删除切片2。

I have a string array: slice1 [][]string. I get the values I want using a for loop:

for _, i := range slice1 { //[string1 string2]
    fmt.Println("server: ", i[1]) //only want the second string in the array.
}

Now I have another string array: slice2 [][]string I get its values using a for loop as well:

for _, value := range output { //
    fmt.Println(value) //Prints: [ 200K, 2, "a", 22, aa-d-2, sd , MatchingString, a ]
}

I want to iterate through slice1 and check if the string2 matches "MatchingString" in Slice2. If it does, don't print the value array.

I created a for loop again to do this but its not working:

for _, value := range slice2 {
    for _, i := range slice1 {
        if strings.Contains(value[0], i[1]) {
            //skip over
        } else {
            fmt.Println(value)
        }
    }
}

Here's a sample code: https://play.golang.org/p/KMVzB2jlbG Any idea on how to do this? Thanks!

  • 写回答

1条回答 默认 最新

  • douao1959 2017-02-18 17:20
    关注

    If I'm reading your question correctly, you are trying to print all those subslices of slice2 that have the property that none of the strings within are the second element of a slice in slice1. If so, you can obtain that through

    Slice2Loop:
        for _, value := range slice2 {
            for _, slice2string := range value {
                for _, i := range slice1 {
                    if slice2string == i[1] {
                        continue Slice2Loop
                    }
                }
            }
            fmt.Println(value)
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀