Scala:映射和元组

来源:转载

映射是键值对偶的集合。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

分享给朋友:
您可能感兴趣的文章:
随机阅读: