Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 生成元组序列而不是映射_Scala_Dictionary_Tuples - Fatal编程技术网

Scala 生成元组序列而不是映射

Scala 生成元组序列而不是映射,scala,dictionary,tuples,Scala,Dictionary,Tuples,这是我的密码。令我惊讶的是,它产生了一个映射,而不是我所期望的元组序列。在scala中获取元组列表的正确方法是什么 for ((_, s) <- Constants.sites; line <- Source.fromFile(s"data/keywords/topkey$s.txt").getLines ) yield ((s, line)) for((uz,s)原因可能是常量。站点是一个映射,因此它返回一个映射 不要在常量.sites上运行理解,而是在

这是我的密码。令我惊讶的是,它产生了一个映射,而不是我所期望的元组序列。在scala中获取元组列表的正确方法是什么

for ((_, s) <- Constants.sites;
         line <- Source.fromFile(s"data/keywords/topkey$s.txt").getLines
    ) yield ((s, line))

for((uz,s)原因可能是
常量。站点
是一个
映射
,因此它返回一个映射

不要在
常量.sites
上运行理解,而是在
常量.sites.values
上运行理解,您仍然只使用这些值

背景是您的代码被翻译为:

Constants.sites.flatMap {
  case (_, s) =>
    Source.fromFile(s"data/keywords/topkey$s.txt").getLines.map {
       line =>
         (s, line)
    }
}
Map
上调用
flatMap
时,生成的类型也需要是
Map
,元组可以强制为
Map

编辑:但使用此选项应该可以:

for {
  (_, s) <- Constants.sites
  line <- Source.fromFile(s"data/keywords/topkey$s.txt").getLines
) yield ((s, line))
用于{

(u,s)您可以将任何映射转换为如下所示的序列:

scala> val m = Map(1->"one", 2 -> "two")
m: scala.collection.immutable.Map[Int,String] = Map(1 -> one, 2 -> two)

scala> m.toSeq
res0: Seq[(Int, String)] = ArrayBuffer((1,one), (2,two))
在你的情况下,你可以这样做

val result = for ((_, s) <- Constants.sites;
         line <- Source.fromFile(s"data/keywords/topkey$s.txt").getLines
    ) yield ((s, line))
result.toSeq

val result=for((uz,s)感谢重构的代码。我尝试了一下,发现flatMap仍然没有像我预期的那样工作。但是,如果我们将flatMap更改为map{}.flatte然后我们将看到tuple2s的flatte Seq。@HuCao wait,更新了我的帖子。
flatMap
map
是Scala为
添加糖分的东西。“原因可能是常量.sites是一个映射,因此它返回一个映射。”+1