我是scala的新手。作为标题,如果键不存在,我想创建一个可变映射Map[Int,(Int, Int)]
并使用默认值作为元组(0,0)。在python中," defaultdict"让这样的努力轻松。在Scala中这样做的优雅方式是什么?
答案 0 :(得分:4)
创建地图后使用withDefaultValue
:
import scala.collection.mutable
val map = mutable.Map[Int,(Int, Int)]().withDefaultValue((0, 0))
答案 1 :(得分:1)
您可能会查看.getOrElseUpdate
,如果不存在具有给定值的更新,则会获取密钥。
scala> val googleMap = Map[Int, (Int, Int)]().empty
googleMap: scala.collection.mutable.Map[Int,(Int, Int)] = Map()
scala> googleMap.getOrElseUpdate(100, (0, 0))
res3: (Int, Int) = (0,0)
scala> googleMap
res4: scala.collection.mutable.Map[Int,(Int, Int)] = Map(100 -> (0,0))
您也可以隐式传递orElse
部分,
scala> implicit val defaultValue = (0, 0)
defaultValue: (Int, Int) = (0,0)
scala> googleMap.getOrElseUpdate(100, implicitly)
res8: (Int, Int) = (0,0)
scala> googleMap
res9: scala.collection.mutable.Map[Int,(Int, Int)] = Map(100 -> (0,0))
答案 2 :(得分:0)
withDefaultValue比getOrElseUpdate简单得多。
import scala.collection.mutable
var kv1 = mutable.Map[Int, Int]().withDefaultValue(0)
var kv2 = mutable.Map[Int, Int]()
kv1(1) += 5 // use default value when key is not exists
kv1(2) = 3
kv2(2) = 3 // both can assign value to a new key.
println(f"kv1(1) ${kv1(1)}, kv1(2) ${kv1(2)} " )
println(f"kv1 ${kv1}")
kv2.getOrElseUpdate(1, 18) // set a default if key not exists
println(f"kv2(1) ${kv2(1)}, kv2(2) ${kv2(2)}")
println(f"kv2 ${kv2}")
输出:
kv1(1)5,kv1(2)3
kv1地图(2-> 3,1-> 5)
kv2(1)18,kv2(2)3
kv2地图(2-> 3,1-> 18)