scala - 在 scala 中将 List[(Int,String)] 转换为 List[Int]
问题描述
我的目标是将文本(索引,行)中的每个单词映射到包含该单词出现的每一行的索引的列表。我设法编写了一个函数,该函数返回分配给索引的所有单词的列表。
以下函数应该完成其余的工作(将索引列表映射到每个单词):
def mapIndicesToWords(l:List[(Int,String)]):Map[String,List[Int]] = ???
如果我这样做:
l.groupBy(x => x._2)
它返回一个Map[String, List[(Int,String)]
. 现在我只想将值更改为 type List[Int]
。我想.mapValues(...)
以某种方式使用和折叠列表,但我是 scala 的新手,不知道正确的方法。
那么如何转换列表呢?
解决方案
您也可以使用 foldLeft,您只需指定累加器(在您的情况下为 Map[String, List[Int]]),它将作为结果返回,并在其中编写一些逻辑。这是我的实现。
def mapIndicesToWords(l:List[(Int,String)]): Map[String,List[Int]] =
l.foldLeft(Map[String, List[Int]]())((map, entry) =>
map.get(entry._2) match {
case Some(list) => map + (entry._2 -> (entry._1 :: list))
case None => map + (entry._2 -> List(entry._1))
}
)
但是使用 foldLeft,列表中的元素将按相反的顺序排列,因此您可以使用 foldRight。只需将 foldLeft 更改为 foldRight 并将输入参数交换(map, entry)
为(entry, map)
.
请注意, foldRight 的工作速度要慢 2 倍。它是使用方法 reverse list 和 foldLeft 实现的。
推荐阅读
- java - 如何为同一布局中的多个按钮设置全局单击侦听器?
- reporting-services - D365 报告中的当前用户网络别名
- php - 在菜单链接项上设置活动类
- django - Typeform Security API 和 Django:未正确验证哈希
- oracle - 需要在plsql代码oracle apex的字符串内连接“”
- angular - Ionic 4 firestoe如何在数据中保存id?
- algorithm - K个散列函数的值,使得误报概率最多为1/n
- node.js - 如何使用 React Node 和 MongoDB 上传和显示 svg 图片?
- tensorflow - 安装 TensorFlow 插件
- javascript - sort() JS 函数没有给出预期的结果