美图欣赏:
一.zip拉链
使用zip方法把元组的多个值绑在一起,以便后续处理
scala> val arr = Array("Jackson", "Make", "Plus")
arr: Array[String] = Array(Jackson, Make, Plus)
scala> val arr2 = Array(1,2,3)
arr2: Array[Int] = Array(1, 2, 3)
scala> arr zip arr2
res0: Array[(String, Int)] = Array((Jackson,1), (Make,2), (Plus,3))
scala> val arr3 = Array(1,2,3,4,5)
arr3: Array[Int] = Array(1, 2, 3, 4, 5)
//注意:如果两个数组的元素个数不一致,拉链操作后生成的数组的长度为较小的那个数组的元素个数
scala> arr zip arr3
res1: Array[(String, Int)] = Array((Jackson,1), (Make,2), (Plus,3))
scala> val arr4 = Array(1,2,3,4,5)
arr4: Array[Int] = Array(1, 2, 3, 4, 5)
scala> val arr5 = Array(6,7,8,9,10)
arr5: Array[Int] = Array(6, 7, 8, 9, 10)
//虽然俩数组也能加起来,但是如果里面元素十分的多,就不提倡了。
scala> Array(arr4(0)+arr5(0),arr4(1)+arr5(1),arr4(2)+arr5(2),arr4(3)+arr5(3),arr4(4)+arr5(4))
res2: Array[Int] = Array(7, 9, 11, 13, 15)
//1.先用zip拉链
scala> (arr4 zip arr5)
res3: Array[(Int, Int)] = Array((1,6), (2,7), (3,8), (4,9), (5,10))
//2. 再用map方法 进行相加
scala> (arr4 zip arr5).map(x => x._1 + x._2)
res4: Array[Int] = Array(7, 9, 11, 13, 15)
拉链扩展
scala> val xs = List(1,2,3)
xs: List[Int] = List(1, 2, 3)
scala> val ys = List('a', 'b')
ys: List[Char] = List(a, b)
scala> val zs = List('q', 'w', 'e', 'r')
zs: List[Char] = List(q, w, e, r)
scala> val x = 0
x: Int = 0
scala> val y = '_'
y: Char = _
scala> val z = " "
z: String = " "
scala> xs.zipAll(ys , x , y)
res8: List[(Int, Char)] = List((1,a), (2,b), (3,_))
//该方法把集合中的每个元素和该元素的索引进行一个拉链操作
scala> val a =List (0,1,2,5,7,9)
a: List[Int] = List(0, 1, 2, 5, 7, 9)
// zipWithIndex函数将元素和其所在的位置索引组成一个pair。
scala> a.zipWithIndex
res11: List[(Int, Int)] = List((0,0), (1,1), (2,2), (5,3), (7,4), (9,5))
//如果索引值想从指定的位置开始,使用zip
scala> a.zip(Stream from 1)
res15: List[(Int, Int)] = List((0,1), (1,2), (2,3), (5,4), (7,5), (9,6))
scala> for ((value,index) <- a.zip(Stream from 1)) println(index+" "+value)
1 0
2 1
3 2
4 5
5 7
6 9
unzip函数可以将一个元组的列表转变成一个列表的元组
scala> val a = Seq(0,1,2,3,4)
a: Seq[Int] = List(0, 1, 2, 3, 4)
scala> val b = Seq(0,1,2,1,3)
b: Seq[Int] = List(0, 1, 2, 1, 3)
scala> a zip b
res17: Seq[(Int, Int)] = List((0,0), (1,1), (2,2), (3,1), (4,3))
scala> res17 unzip
warning: there was one feature warning; re-run with -feature for details
res18: (Seq[Int], Seq[Int]) = (List(0, 1, 2, 3, 4),List(0, 1, 2, 1, 3))
————保持饥饿,保持学习
Jackson_MVP
来源:CSDN
作者:Jackson_MVP
链接:https://blog.csdn.net/Jackson_mvp/article/details/104651627