dictionary - 去确定字符串 slice 上单词出现的次数

标签 dictionary go slice

尝试用我编写的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,即0int,它将告诉您被发现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/

相关文章:

c++ - 当通过 const 引用传递的对象被添加到像 std::map 这样的容器时会发生什么?

python - 删除字典中列表中的所有值

c# - Lambda 表达式作为字典中的键

Go 进程在捕获 SIGINT 和 SIGTERM 时过早死亡

javascript - 使用 GoLang http.FileServer 时找不到 React 脚本

go - PubSub 不确认消息

C++ map<std::string> vs map<char *> 性能(我知道, "again?")

Python,将索引列表转换为切片

python - 我如何从Python中的s[-4 :] to s[slice(? ??)] 进行翻译?不是“s[切片(s, len(s))]”

javascript - 为什么这段 javascript 会给出不同的结果?