use*_*790 3 grouping scala map
我是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的一些示例,似乎没有任何帮助我的用例.有任何想法吗?
根据您的描述,您的计数功能应该使用单词而不是单词列表.我会这样定义:
def countFunction(words: String): List[(String, Int)]
Run Code Online (Sandbox Code Playgroud)
如果你这样做,你应该可以打电话words.groupBy(countFunction),这与:
words.groupBy(word => countFunction(word))
Run Code Online (Sandbox Code Playgroud)
如果您无法更改签名countFunction,那么您应该能够像这样调用group:
words.groupBy(word => countFunction(List(word)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13262 次 |
| 最近记录: |