产生一个元组序列而不是map [英] Yield a sequence of tuples instead of map

查看:95
本文介绍了产生一个元组序列而不是map的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码。令我惊讶的是,它生成的是一个映射,而不是我期望的一系列元组。在scala中获取元组列表的正确方法是什么?

This is my code. To my surprise, it yields a map instead of a seq of tuples as I expect. What is right way to get list of tuples in scala?

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


推荐答案

原因可能是 Constants.sites Map ,因此它会返回地图。

The reason probably is that Constants.sites is a Map, therefore it returns a map.

而不是对进行理解Constants.sites ,在 Constants.sites.values 上运行,无论如何,您仅使用这些值。

Instead of running the comprehension over Constants.sites, run it over Constants.sites.values, you are only using the values anyway.

背景是您的代码被转换为:

The background is that your code gets translated to:

Constants.sites.flatMap {
  case (_, s) =>
    Source.fromFile(s"data/keywords/topkey$s.txt").getLines.map {
       line =>
         (s, line)
    }
}

何时在 Map 上调用 flatMap 您得到的类型也需要是 Map ,并且元组可以强制到 Map

And when calling flatMap on Map your resulting type also needs to be a Map, and the tuples can be coerced to a Map.

编辑:但是使用它应该没问题:

But using this should be fine:

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

这篇关于产生一个元组序列而不是map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆