Lou*_*nda 1 dictionary go 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
}
Run Code Online (Sandbox Code Playgroud)
输出以下内容
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]
Run Code Online (Sandbox Code Playgroud)
PS:go strings.Count 只统计字符串,而不统计[]字符串。
您当前要做的就是收集不同的元素并将它们的索引分配给它们。如果一个单词出现多次,则将为其分配最高索引。
正如您所说,您想要计算单词数。因此,代替索引,为新单词(第一次出现)分配 1,如果它已经在映射中,则将其值增加 1。
由于您可以使用不存在的键对映射进行索引,在这种情况下,结果是映射的值类型的零值0,即for int,它会告诉您它被找到了0几次(到目前为止),所以您不需要甚至不必检查密钥是否已经存在,只需继续并增加它:
dict[v]++
Run Code Online (Sandbox Code Playgroud)
所以CountOccurrences()可能看起来像这样:
func CountOccurence(apps []string) map[string]int {
dict := make(map[string]int)
for _, v := range apps {
fmt.Println(v)
dict[v]++
}
return dict
}
Run Code Online (Sandbox Code Playgroud)
它将输出(在Go Playground上尝试):
apps: [one two three one four]
one
two
three
one
four
=== o: map[four:1 one:2 three:1 two:1]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1596 次 |
| 最近记录: |