go - 如何从一组数组中过滤出一个数组,其中一个数组中的所有项目都与另一个数组中的某些项目匹配?

标签 go

TL/DR

如何根据字符串数组过滤数组数组?

Go 中是否有 JS/Py 的 someany 等效项,如果数组中的部分或全部项目存在于其中,我可以过滤数组的数组另一个数组?

例如,将其视为源数组:

arrays := [][]string{
        {"some", "value"},
        {"some", "value", "another"},
        {"value", "another", "test"},
        {"value", "test"},
        {"some", "test"},
    }

如果这里的所有项目都在数组中找到,我想通过 []string{"some", "value"} 过滤数组

预期输出是

[[some value] [some value another]]

或者,如果我将过滤器更改为 []string{"some", "test"},则预期值为 [[some test]]

我可以在我的测试代码中完全正确地理解逻辑

package main

import "fmt"

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

func main() {
    arrays := [][]string{
        {"some", "value"},
        {"some", "value", "another"},
        {"value", "another", "test"},
        {"value", "test"},
        {"some", "test"},
    }
    filterBy := []string{"some", "value"}
    hold := make([][]string, 0)
    // Ignore this because it doesnt work as expected
    for _, arr := range arrays {
        for _, f := range filterBy {
            if ok := inArray(f, arr); ok {
                hold = append(hold, arr)
            }
        }
    }
    fmt.Println(hold)
}

最佳答案

inArray 函数中的逻辑对于检查单针 s string 是否在大海捞针 arr []string 中是正确的。如果您想扩展它来检查所有ss []string是否存在于干草堆arr []string中,那么您至少也需要在针上绕一圈。这是一个例子:

func allInArray(ss []string, arr []string) bool {
    for _, s := range ss {
        if !inArray(s, arr) {
            return false
        }
    }
    return true
}

Here is a working example in the playgound.

当然,这是相当低效的,因为它在干草堆 arr 上循环的次数与 ss 中的针数一样多。为了提高效率,您可以预处理干草堆,将其转换为 map[string]struct{},然后对照 map 的键检查针,如下所示:

func allInArray(ss []string, arr []string) bool {
    present := make(map[string]struct{})
    for _, a := range arr {
        present[a] = struct{}{}
    }
    for _, s := range ss {
        if _, ok := present[s]; !ok {
            return false
        }
    }
    return true
}

Here is a working example in the playground.

它会迭代 arr 一次以创建查找映射,然后迭代 ss 一次,利用映射的恒定查找时间来检查是否存在ss 元素存在于 arr 中。

关于go - 如何从一组数组中过滤出一个数组,其中一个数组中的所有项目都与另一个数组中的某些项目匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61803288/

相关文章:

Golang 从串行读取

docker - go get golang-migrate inside of docker 错误

unicode - 如何检索 []rune 的第一个 “complete” 字符?

ajax - 如何使用 Protocol Buffer 序列化 Go 结构并在 Dart over Ajax 中使用它们

linux - 有没有相当于ps的go命令?

go - 为什么此Go/GraphQL查询返回HTTP 415错误?

mysql - 使用 slice 执行 sql 准备语句

mongodb - MongoDB Compass Filter表达式转换为Go bson.M表达式

mysql - 如何在 Go 中为 MySQL 构建 RESTful API?

android - 在android和go之间使用RSA