list - 鉴于字符串列表表示 Scala 中映射的键,如何将 List[String] 转换为 List[Map[String,String]]?
问题描述
我有一个清单references
:
val references: List[String]= List("S","R")
我也有variables
:
val variables: Map[String,List[String]]=("S"->("a","b"),"R"->("west","east"))
references
是变量映射的键列表。
我想构造一个函数,它需要:
def expandReplacements(references:List[String],variables:Map[String,List[String]]):List[Map(String,String)]
这个函数基本上应该创建返回以下组合
List(Map("S"->"a"),("R"->"west"),Map("S"->"a"),("R"->"east"),Map("S"->"b"),("R"->"west"),Map("S"->"b"),("R"->"east"))
我试过这样做:
val variables: Map[String,List[String]] = Map("S" -> List("a", "b"), "R" -> List("east", "central"))
val references: List[String] = List("S","R")
def expandReplacements(references: List[String]): List[Map[String, String]] =
references match {
case ref :: refs =>
val variableValues =
variables(ref)
val x = variableValues.flatMap { variableValue =>
val remaining = expandReplacements(refs)
remaining.map(rem => rem + (ref -> variableValue))
}
x
case Nil => List.empty
}
解决方案
如果您有超过 2 个参考,您可以执行以下操作:
def expandReplacements(references: List[String], variables :Map[String,List[String]]): List[Map[String, String]] = {
references match {
case Nil => List(Map.empty[String, String])
case x :: xs =>
variables.get(x).fold {
expandReplacements(xs, variables)
} { variableList =>
for {
variable <- variableList.map(x -> _)
otherReplacements <- expandReplacements(xs, variables)
} yield otherReplacements + variable
}
}
}
代码在Scastie运行。
推荐阅读
- javascript - 在解析中返回另一个 aysnc 函数
- r - 使用 R 从多个 excel 文件中提取特定单元格
- react-native - React Native 错误:带有有效负载 {"name":"GameScreen"} 的操作 'NAVIGATE' 未被任何导航器处理
- javascript - 关闭 iframe 模式时如何停止 youtube 视频
- python - 为什么我无法在 selenium webdriver python 上单击此按钮?
- amazon-s3 - 如何在 Kafka Connect S3 中解析记录头?
- java - Spring-Boot:带参数的注入?
- python - 在客户数据中查找首次购买的月份
- c# - RegistryKey 类中的 ValidateKeyView 有什么意义?
- java - 使用 Proguard 混淆 Spring Boot fat Jar