1,"B"->2) map2 = new HashMap("B"->22,"D"->4) // B i-6ren">
gpt4 book ai didi

scala - 压缩两个 HashMap(或字典)

转载 作者:行者123 更新时间:2023-12-03 17:50:59 24 4
gpt4 key购买 nike

在 Scala 中压缩两个字典的功能方法是什么?

map1 = new HashMap("A"->1,"B"->2)
map2 = new HashMap("B"->22,"D"->4) // B is the only common key
zipper(map1,map2)应该给出类似的东西
 Seq( ("A",1,0), // no A in second map, so third value is zero
("B",2,22),
("D",0,4)) // no D in first map, so second value is zero

如果不实用,任何其他风格也值得赞赏

最佳答案

def zipper(map1: Map[String, Int], map2: Map[String, Int]) = {
for(key <- map1.keys ++ map2.keys)
yield (key, map1.getOrElse(key, 0), map2.getOrElse(key, 0))
}


scala> val map1 = scala.collection.immutable.HashMap("A" -> 1, "B" -> 2)
map1: scala.collection.immutable.HashMap[String,Int] = Map(A -> 1, B -> 2)

scala> val map2 = scala.collection.immutable.HashMap("B" -> 22, "D" -> 4)
map2: scala.collection.immutable.HashMap[String,Int] = Map(B -> 22, D -> 4)

scala> :load Zipper.scala
Loading Zipper.scala...
zipper: (map1: Map[String,Int], map2: Map[String,Int])Iterable[(String, Int, Int)]

scala> zipper(map1, map2)
res1: Iterable[(String, Int, Int)] = Set((A,1,0), (B,2,22), (D,0,4))

注意使用 get可能比 getOrElse 更可取在这种情况下。 None用于指定值不存在而不是使用 0 .

关于scala - 压缩两个 HashMap(或字典),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16258230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com