亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

基于線性時間中多個條件的切片中的廣義計數元素

基于線性時間中多個條件的切片中的廣義計數元素

Go
三國紛爭 2022-08-09 20:22:26
我需要以許多不同的方式在長數組中計算元素。下面是特殊情況的用例示例: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)}這將打印計數A: 2, 計數$: 2, 計數A$: 1https://play.golang.org/p/R0nhwFpyN7H現在的問題是:有沒有辦法對此進行泛化,以便我可以在數組的一次迭代中根據屬性計算不同的總和,而無需單獨實現每種情況?編輯2:這是一個基于用戶Volker建議的稍微好一點的版本: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:這是一個進一步的推廣,接受多個計數器。感謝Volker和Eli的投入。也許這些來源對其他人也有用。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)}編輯:我也愿意接受關于如何改進問題的建議。這是我遇到的一個合法問題,一般方法將大大簡化我的代碼。
查看完整描述

1 回答

?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

Go中沒有特別的醬汁可以做到這一點。您需要在切片上編寫一個循環 - 沒關系。


您的原始代碼絕對沒問題,特別是如果您需要在同一循環中執行多個不同的計數。該函數也很好,它抽象出一些代碼(雖然不多),但它只對單個計數器有用 - 單個過濾器/測試函數。count2


你可以繼續推廣它,例如,傳入一個結構切片,其中每個結構都是:Metrics


type Metrics struct {

  Counter int

  Filter func(test) bool

}

這完全取決于您的確切需求。


如果你在這里尋找慣用的Go方式:不要太擔心過早的抽象。編寫最清晰/最易讀的代碼來解決眼前的任務。


查看完整回答
反對 回復 2022-08-09
  • 1 回答
  • 0 關注
  • 107 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號