我需要以許多不同的方式在長數(shù)組中計(jì)算元素。下面是特殊情況的用例示例:func main() { test := []test{test{"A", "1", "$"}, test{"A", "2", "€"}, test{"B", "3", "$"}} countA := 0 countDollar := 0 countADollar := 0 for _, e := range test { if e.prop1 == "A" { countA++ } if e.prop3 == "$" { countDollar++ } if e.prop1 == "A" && e.prop3 == "$" { countADollar++ } } fmt.Printf("countA: %v, count$: %v, countA$: %v\n", countA, countDollar, countADollar)}這將打印計(jì)數(shù)A: 2, 計(jì)數(shù)$: 2, 計(jì)數(shù)A$: 1https://play.golang.org/p/R0nhwFpyN7H現(xiàn)在的問題是:有沒有辦法對(duì)此進(jìn)行泛化,以便我可以在數(shù)組的一次迭代中根據(jù)屬性計(jì)算不同的總和,而無需單獨(dú)實(shí)現(xiàn)每種情況?編輯2:這是一個(gè)基于用戶Volker建議的稍微好一點(diǎn)的版本:package mainimport "fmt"type test struct { prop1 string prop2 string prop3 string}func count2(data []test, f func(test) bool) { count1 := 0; for _, e := range data { if f(e) { count1++ } } fmt.Printf("count1: %v", count1)}func main() { data := []test{test{"A", "1", "$"}, test{"A", "2", "€"}, test{"B", "3", "$"}} myTestCrit := func(t test) bool { return t.prop1 == "A" } count2(data, myTestCrit)}https://play.golang.org/p/kB60gJCBkyn編輯3:這是一個(gè)進(jìn)一步的推廣,接受多個(gè)計(jì)數(shù)器。感謝Volker和Eli的投入。也許這些來源對(duì)其他人也有用。func count3(data []test, f []func(test) bool) { counts := make([]int, len(f)); for _, e := range data { for i, fi := range f { if fi(e) { counts[i]++ } } } fmt.Printf("counts: %v\n", counts)}func main() { data := []test{test{"A", "1", "$"}, test{"A", "2", "€"}, test{"B", "3", "$"}} myTestCrit := func(t test) bool { return t.prop1 == "A" } myTestCritDollar := func(t test) bool { return t.prop3 == "$" } countCrits := make([]func(t test) bool, 2) countCrits[0] = myTestCrit countCrits[1] = myTestCritDollar count3(data, countCrits)}編輯:我也愿意接受關(guān)于如何改進(jìn)問題的建議。這是我遇到的一個(gè)合法問題,一般方法將大大簡(jiǎn)化我的代碼。
基于線性時(shí)間中多個(gè)條件的切片中的廣義計(jì)數(shù)元素
三國紛爭(zhēng)
2022-08-09 20:22:26