确定字符串切片上单词出现的次数



很难弄清楚如何使用我编写的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字符串。Count只计算字符串,不计算[]字符串

您当前所做的是收集不同的元素并为它们分配索引。如果一个单词出现多次,将为其分配最高索引。

正如你所说的,你要数单词。因此,代替索引,为新单词(第一次出现)赋值1,如果它已经在映射中,则将其值增加1。

因为你可以用一个不存在的键来索引一个映射,在这种情况下,结果是映射值类型的零值,也就是int0,它会告诉你它已经找到了0次(到目前为止),所以你甚至不必检查键是否已经在那里,只要继续增加它:

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
}

将输出(在Go Playground上试试):

apps: [one two three one four]
one
two
three
one
four
=== o:  map[four:1 one:2 three:1 two:1]

最新更新