映射是鍵值對偶的集合。Scala有一個通用的叫法——元組:n個對象的聚集,並不一定要相同的類型。 構造映射 鍵A -> 值B scala> val scores = Map("wcc100"->100)//不可變映射 scores: scala.collection.immutable.Map[St ...
映射是鍵值對偶的集合。Scala有一個通用的叫法——元組:n個對象的聚集,並不一定要相同的類型。
構造映射
鍵A -> 值B
scala> val scores = Map("wcc100"->100)//不可變映射 scores: scala.collection.immutable.Map[String,Int] = Map(wcc100 -> 100) scala> val scores1 = scala.collection.mutable.Map("wcc100"->100)//可變的映射 scores1: scala.collection.mutable.Map[String,Int] = Map(wcc100 -> 100)
獲取映射中的值
類似python中字典的取值
scala> val value = scores("wcc100") value: Int = 100
判斷鍵並取值
getOrElse類比r(ifelse),python(np.where)
scala> val p = if(scores.contains("wcc100")) scores("wcc100") else 0 p: Int = 100 scala> val p1 = scores.getOrElse("wcc100",0) p1: Int = 100
更新可變映射
scala> scores1 += ("w" -> 1,"cc" -> 2) res1: scores1.type = Map(w -> 1, wcc100 -> 100, cc -> 2) scala> scores1 -= "wcc100" res2: scores1.type = Map(w -> 1, cc -> 2) scala> scores1.keySet res3: scala.collection.Set[String] = Set(w, cc) scala> scores1.values res4: Iterable[Int] = HashMap(1, 2)
迭代映射
反轉映射
scala> for((k,v)<-scores1) yield(v,k) res5: scala.collection.mutable.Map[Int,String] = Map(2 -> cc, 1 -> w)
元組
scala> val t = (1,1.1,"fre") t: (Int, Double, String) = (1,1.1,fre) scala> t._1 res6: Int = 1 scala> t._3 res7: String = fre scala> "Wcc".partition(_.isUpper) res8: (String, String) = (W,cc)
拉鏈操作
keys.zip(values).toMap
scala> val keys = Array("a","b","c") keys: Array[String] = Array(a, b, c) scala> val values = Array(1,2,3) values: Array[Int] = Array(1, 2, 3) scala> val pairs = keys.zip(values).toMap pairs: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)
本文鏈接:http://www.cnblogs.com/homewch/p/5808548.html