scala元组及拉链操作:
scala里面的元组是可是不同数据类型的
scala> ("scala",1)
res45: (String, Int) = (scala,1)
scala> val t = ("scala",100L,3.14,("spark",1))
t: (String, Long, Double, (String, Int)) = (scala,100,3.14,(spark,1))
scala> t._1 //元组内空的提取,以下标为1开始,并用._后跟数字的方式进行提取内容
res46: String = scala
scala> t._3
res47: Double = 3.14
scala> t._4._1
res48: String = spark
scala> val t,(a,b,c,d) = ("scala",100L,3.14,("spark",1)) //可以定义元组时给予变量名,如 t,(a, b, c, d),使用时直接用变量名a,b,c,d即可访问对应内容
t: (String, Long, Double, (String, Int)) = (scala,100,3.14,(spark,1))
a: String = scala
b: Long = 100
c: Double = 3.14
d: (String, Int) = (spark,1)
scala> a
res49: String = scala
scala> val arr = Array(("tingting",1),("ningning",3),("huihui",5))
arr: Array[(String, Int)] = Array((tingting,1), (ningning,3), (huihui,5))
scala> val mp = arr.toMap
mp: scala.collection.immutable.Map[String,Int] = Map(tingting -> 1, ningning -> 3, huihui -> 5)
scala拉链操作:
scala> val arr1 = Array("dog","cat","mouse")
arr1: Array[String] = Array(dog, cat, mouse)
scala> val arr2 = Array(1,3,5)
arr2: Array[Int] = Array(1, 3, 5)
scala> arr1 zip arr2 //拉链操作符
res50: Array[(String, Int)] = Array((dog,1), (cat,3), (mouse,5))
scala> arr2 zip arr1 //拉链操作符
res51: Array[(Int, String)] = Array((1,dog), (3,cat), (5,mouse))
scala> arr1.zip(arr2) //拉链操作符
res52: Array[(String, Int)] = Array((dog,1), (cat,3), (mouse,5))
scala> val arr3 = Array(1,2,3,4,5) //生成一个比arr1元素多的数组,用少的去zip多的
arr3: Array[Int] = Array(1, 2, 3, 4, 5)
scala> arr1 zip arr3 //会把长的给截取掉了
res53: Array[(String, Int)] = Array((dog,1), (cat,2), (mouse,3))