尝试用我编写的go-lang代码很难计算出 slice 中的应用程序或单词的数量。
希望有人可以帮助我弄清楚如何计算发生次数?
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:转到字符串。Count只计算一个字符串,不计算[]字符串。
最佳答案
当前您要做的是收集不同的元素,然后将它们分配给它们。如果单词多次出现,则会为其分配最高索引。
如您所说,您要数字。因此,要为新单词(第一次出现)分配1而不是索引,如果它已经在 map 中,则将其值增加1。
由于您可以使用不存在的键index映射,在这种情况下,结果是映射的值类型的zero value,即0
的int
,它将告诉您被发现0
的时间(到目前为止),因此您甚至不必检查 key 是否已在其中,只需继续进行递增操作即可:
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]
关于dictionary - 去确定字符串 slice 上单词出现的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65900501/