首页 > 解决方案 > 在 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 的新手,不知道正确的方法。

那么如何转换列表呢?

标签: scalafunctional-programming

解决方案


您也可以使用 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 实现的。


推荐阅读