gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:08:38 27 4
gpt4 key购买 nike

TL/DR

如何针对字符串数组过滤数组数组?

是否有一个JS/Py的someany等效项,如果一个数组中的某些或所有项目都存在于另一个数组中,那么我可以过滤一个数组数组?

因此,例如,将其视为源数组:

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

如果要在数组中找到所有此处的项目,我想按 arrays过滤 []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.

当然,这是相当低效的,因为它在hayt 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com