小编use*_*790的帖子

Scala映射和/或groupby函数

我是Scala的新手,我正试图找出一些scala语法.

所以我有一个字符串列表.

wordList: List[String] = List("this", "is", "a", "test")
Run Code Online (Sandbox Code Playgroud)

我有一个函数返回一个对列表,其中包含每个单词的辅音和元音计数:

def countFunction(words: List[String]): List[(String, Int)]
Run Code Online (Sandbox Code Playgroud)

所以,例如:

countFunction(List("test")) => List(('Consonants', 3), ('Vowels', 1))
Run Code Online (Sandbox Code Playgroud)

我现在想要一个单词列表并按计数签名对它们进行分组:

def mapFunction(words: List[String]): Map[List[(String, Int)], List[String]]

//using wordList from above
mapFunction(wordList) => List(('Consonants', 3), ('Vowels', 1)) -> Seq("this", "test")
                         List(('Consonants', 1), ('Vowels', 1)) -> Seq("is")
                         List(('Consonants', 0), ('Vowels', 1)) -> Seq("a")
Run Code Online (Sandbox Code Playgroud)

我想我需要使用GroupBy来做到这一点:

def mapFunction(words: List[String]): Map[List[(String, Int)], List[String]] = { 
    words.groupBy(F: (A) => K)
}
Run Code Online (Sandbox Code Playgroud)

我已经阅读了Map.GroupBy的scala api,看到F代表鉴别器功能,K是你想要返回的键的类型.所以我尝试了这个:

    words.groupBy(countFunction => List[(String, Int)]
Run Code Online (Sandbox Code Playgroud)

但是,scala不喜欢这种语法.我尝试查找groupBy的一些示例,似乎没有任何帮助我的用例.有任何想法吗?

grouping scala map

3
推荐指数
1
解决办法
1万
查看次数

标签 统计

grouping ×1

map ×1

scala ×1