TL/DR
如何根据字符串数组过滤数组数组?
Go 中是否有 JS/Py 的 some
或 any
等效项,如果数组中的部分或全部项目存在于其中,我可以过滤数组的数组另一个数组?
例如,将其视为源数组:
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/