dongyan2469 2018-01-31 19:26
浏览 1365
已采纳

如何在GO中检查切片是否在切片中?

I have the following code:

func main(){
    l1 := []string{"a", "b", "c"}
    l2 := []string {"a", "c"}
    //l2 in l1?
}

I can check this using loops and flags but Is there a simple way to check if l2 is inside l1 like python command "l2 in l1"?

  • 写回答

3条回答 默认 最新

  • douhui1333 2018-01-31 19:39
    关注

    Following from How to check if a slice is inside a slice in GO?, @Mostafa posted the following for checking if an element is in a slice:

    func contains(s []string, e string) bool {
       for _, a := range s {
            if a == e {
                return true
            }
        }
        return false
    }
    

    Now it's a matter of checking element by element:

    func subslice (s1 []string, s2 []string) bool {
        if len(s1) > len(s2) { return false }
        for _, e := range s1 {
            if ! contains(s2,e) {
                return false
            }
        }
        return true
    }
    

    Of course, this ignores duplicates, so there's room for improvement.

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?