[英]Go determine number of word occurences on a string slice
很難弄清楚如何使用我制作的 go-lang 代碼計算切片上的應用程序或單詞的數量。
希望有人能幫我弄清楚如何計算出現次數?
https://play.golang.org/p/KvgI-lCz_c6
package main
import (
"fmt"
)
func main() {
apps := []string{"one", "two", "three", "one", "four"}
fmt.Println("apps:", apps)
o := CountOccurence(apps)
fmt.Println("=== o: ", o)
}
func CountOccurence(apps []string) map[string]int {
dict := make(map[string]int)
for k, v := range apps {
fmt.Println(k, v)
dict[v] = k
}
// fmt.Println("=== dict: ", dict)
return dict
}
輸出以下內容
apps: [one two three one four]
0 one
1 two
2 three
3 one
4 four
=== o: map[four:4 one:3 three:2 two:1]
PS:go strings.Count 只計算一個字符串,而不是一個 [] 字符串。
您當前所做的是收集不同的元素並將它們的索引分配給它們。 如果一個詞出現多次,最高的索引將被分配給它。
正如你所說,你想數單詞。 因此,不是索引,而是為新單詞(第一次出現)分配 1,如果它已經在 map 中,則將其值增加 1。
由於您可以使用不存在的鍵索引map,在這種情況下,結果是 map 的值類型的零值,對於int
為0
,它會告訴您它被找到0
次(到目前為止),所以你甚至不必檢查一個鍵是否已經在那里,只需 go 並增加它:
dict[v]++
所以CountOccurrences()
可能看起來像這樣:
func CountOccurence(apps []string) map[string]int {
dict := make(map[string]int)
for _, v := range apps {
fmt.Println(v)
dict[v]++
}
return dict
}
哪個將 output (在Go Playground上嘗試):
apps: [one two three one four]
one
two
three
one
four
=== o: map[four:1 one:2 three:1 two:1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.