【问题标题】:Simple Scala coding question简单的 Scala 编码问题
【发布时间】:2011-09-04 09:56:43
【问题描述】:

假设我有List[String] 类型的列表countriesMap[String, String] 类型的映射capitals。现在我想写一个函数

pairs(countries:List[String], capitals:Map[String, String]):Seq[(String, String)]
返回对(country, capital)的序列,如果大写则打印错误对于某些国家/地区未找到。最好的方法是什么?

【问题讨论】:

    标签: scala


    【解决方案1】:

    首先,您的Map[String,String]已经Seq[(String,String)],如果您愿意,可以通过调用toSeq 来正式化:

    val xs = Map("UK" -> "London", "France" -> "Paris")
    xs.toSeq
    // yields a Seq[(String, String)]
    

    所以问题归结为寻找不在地图上的国家。您有两种方法可以获取 代表的那些国家/地区的集合。

    keys 方法将返回 Iterator[String],而 keySet 将返回 Set[String]。让我们支持后者:

    val countriesWithCapitals = xs.keySet
    val allCountries = List("France", "UK", "Italy")
    val countriesWithoutCapitals = allCountries.toSet -- countriesWithCapitals
    //yields Set("Italy")
    

    以您认为合适的任何方式将其转换为错误。

    【讨论】:

    • 您是否假设国家列表是地图键的超集?主要目标可能是显示一小部分国家的首都,而不是在地图中找到缺失的国家。不过,这个问题并不完全清楚。
    • @Ben - 我正在根据描述工作:“如果找不到某个国家/地区的首都,则打印错误”
    【解决方案2】:
    countries.map(x=>(x, capitals(x)))
    

    【讨论】:

      猜你喜欢
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      相关资源
      最近更新 更多