1. 程式人生 > >Scala 強大的集合資料操作示例

Scala 強大的集合資料操作示例

Scala是資料探勘演算法領域最有力的程式語言之一,語言本身是面向函式,這也符合了資料探勘演算法的常用場景:在原始資料集上應用一系列的變換,語言本身也對集合操作提供了眾多強大的函式,本文將以List型別為例子,介紹常見的集合變換操作。

一、常用操作符(操作符其實也是函式) ++ ++[B](that: GenTraversableOnce[B]): List[B] 從列表的尾部新增另外一個列表

++: ++:[B >: A, That](that: collection.Traversable[B])(implicit bf: CanBuildFrom[List[A], B, That]): That 在列表的頭部新增一個列表

+: +:(elem: A): List[A] 在列表的頭部新增一個元素

:+ :+(elem: A): List[A] 在列表的尾部新增一個元素

:: ::(x: A): List[A] 在列表的頭部新增一個元素

::: :::(prefix: List[A]): List[A] 在列表的頭部新增另外一個列表

:\ :[B](z: B)(op: (A, B) ⇒ B): B 與foldRight等價

val left = List(1,2,3) val right = List(4,5,6)

//以下操作等價 left ++ right // List(1,2,3,4,5,6) left ++: right // List(1,2,3,4,5,6) right.++:(left) // List(1,2,3,4,5,6) right.:::(left) // List(1,2,3,4,5,6)

//以下操作等價 0 +: left //List(0,1,2,3) left.+:(0) //List(0,1,2,3)

//以下操作等價 left :+ 4 //List(1,2,3,4) left.:+(4) //List(1,2,3,4)

//以下操作等價 0 :: left //List(0,1,2,3) left.::(0) //List(0,1,2,3) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 看到這裡大家應該跟我一樣有一點暈吧,怎麼這麼多奇怪的操作符,這裡給大家一個提示,任何以冒號結果的操作符,都是右繫結的,即 0 :: List(1,2,3) = List(1,2,3).::(0) = List(0,1,2,3) 從這裡可以看出操作::其實是右邊List的操作符,而非左邊Int型別的操作符

二、常用變換操作 1.map

map[B](f: (A) ⇒ B): List[B]

定義一個變換,把該變換應用到列表的每個元素中,原列表不變,返回一個新的列表資料

Example1 平方變換

val nums = List(1,2,3) val square = (x: Int) => xx
val squareNums1 = nums.map(num => num
num) //List(1,4,9) val squareNums2 = nums.map(math.pow(_,2)) //List(1,4,9) val squareNums3 = nums.map(square) //List(1,4,9) 1 2 3 4 5 Example2 儲存文字資料中的某幾列

val text = List("Homeway,25,Male","XSDYM,23,Female") val usersList = text.map(_.split(",")(0))
val usersWithAgeList = text.map(line => { val fields = line.split(",") val user = fields(0) val age = fields(1).toInt (user,age) }) 1 2 3 4 5 6 7 8 9 2.flatMap, flatten

flatten: flatten[B]: List[B] 對列表的列表進行平坦化操作 flatMap: flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): List[B] map之後對結果進行flatten

定義一個變換f, 把f應用列表的每個元素中,每個f返回一個列表,最終把所有列表連結起來。

val text = List("A,B,C","D,E,F") val textMapped = text.map(.split(",").toList) // List(List("A","B","C"),List("D","E","F")) val textFlattened = textMapped.flatten // List("A","B","C","D","E","F") val textFlatMapped = text.flatMap(.split(",").toList) // List("A","B","C","D","E","F") 1 2 3 4 5 3.reduce

reduce[A1 >: A](op: (A1, A1) ⇒ A1): A1

定義一個變換f, f把兩個列表的元素合成一個,遍歷列表,最終把列表合併成單一元素

Example 列表求和

val nums = List(1,2,3) val sum1 = nums.reduce((a,b) => a+b) //6 val sum2 = nums.reduce(+) //6 val sum3 = nums.sum //6 1 2 3 4 5 6 4.reduceLeft,reduceRight

reduceLeft: reduceLeft[B >: A](f: (B, A) ⇒ B): B

reduceRight: reduceRight[B >: A](op: (A, B) ⇒ B): B

reduceLeft從列表的左邊往右邊應用reduce函式,reduceRight從列表的右邊往左邊應用reduce函式

Example

val nums = List(2.0,2.0,3.0) val resultLeftReduce = nums.reduceLeft(math.pow) // = pow( pow(2.0,2.0) , 3.0) = 64.0 val resultRightReduce = nums.reduceRight(math.pow) // = pow(2.0, pow(2.0,3.0)) = 256.0 1 2 3 4 5 5.fold,foldLeft,foldRight

fold: fold[A1 >: A](z: A1)(op: (A1, A1) ⇒ A1): A1 帶有初始值的reduce,從一個初始值開始,從左向右將兩個元素合併成一個,最終把列表合併成單一元素。

foldLeft: foldLeft[B](z: B)(f: (B, A) ⇒ B): B 帶有初始值的reduceLeft

foldRight: foldRight[B](z: B)(op: (A, B) ⇒ B): B 帶有初始值的reduceRight

val nums = List(2,3,4) val sum = nums.fold(1)(+) // = 1+2+3+4 = 9

val nums = List(2.0,3.0) val result1 = nums.foldLeft(4.0)(math.pow) // = pow(pow(4.0,2.0),3.0) = 4096 val result2 = nums.foldRight(1.0)(math.pow) // = pow(1.0,pow(2.0,3.0)) = 8.0 1 2 3 4 5 6 7 8 6.sortBy,sortWith,sorted

sortBy: sortBy[B](f: (A) ⇒ B)(implicit ord: math.Ordering[B]): List[A] 按照應用函式f之後產生的元素進行排序

sorted: sorted[B >: A](implicit ord: math.Ordering[B]): List[A] 按照元素自身進行排序

sortWith: sortWith(lt: (A, A) ⇒ Boolean): List[A] 使用自定義的比較函式進行排序

val nums = List(1,3,2,4) val sorted = nums.sorted //List(1,2,3,4)

val users = List(("HomeWay",25),("XSDYM",23)) val sortedByAge = users.sortBy{case(user,age) => age} //List(("XSDYM",23),("HomeWay",25)) val sortedWith = users.sortWith{case(user1,user2) => user1._2 < user2._2} //List(("XSDYM",23),("HomeWay",25)) 1 2 3 4 5 6 7 7.filter, filterNot

filter: filter(p: (A) ⇒ Boolean): List[A]

filterNot: filterNot(p: (A) ⇒ Boolean): List[A]

filter 保留列表中符合條件p的列表元素 , filterNot,保留列表中不符合條件p的列表元素

val nums = List(1,2,3,4) val odd = nums.filter( _ % 2 != 0) // List(1,3) val even = nums.filterNot( _ % 2 != 0) // List(2,4) 1 2 3 4 8.count

count(p: (A) ⇒ Boolean): Int

計算列表中所有滿足條件p的元素的個數,等價於 filter(p).length

val nums = List(-1,-2,0,1,2) val plusCnt1 = nums.count( > 0) val plusCnt2 = nums.filter( > 0).length 9. diff, union, intersect

diff:diff(that: collection.Seq[A]): List[A] 儲存列表中那些不在另外一個列表中的元素,即從集合中減去與另外一個集合的交集

union : union(that: collection.Seq[A]): List[A] 與另外一個列表進行連結

intersect: intersect(that: collection.Seq[A]): List[A] 與另外一個集合的交集

val nums1 = List(1,2,3) val nums2 = List(2,3,4) val diff1 = nums1 diff nums2 // List(1) val diff2 = nums2.diff(num1) // List(4) val union1 = nums1 union nums2 // List(1,2,3,2,3,4) val union2 = nums2 ++ nums1 // List(2,3,4,1,2,3) val intersection = nums1 intersect nums2 //List(2,3) 1 2 3 4 5 6 7 10.distinct

distinct: List[A] 保留列表中非重複的元素,相同的元素只會被保留一次

val list = List("A","B","C","A","B") val distincted = list.distinct // List("A","B","C") 1 11.groupBy, grouped

groupBy : groupBy[K](f: (A) ⇒ K): Map[K, List[A]] 將列表進行分組,分組的依據是應用f在元素上後產生的新元素 grouped: grouped(size: Int): Iterator[List[A]] 按列表按照固定的大小進行分組

val data = List(("HomeWay","Male"),("XSDYM","Femail"),("Mr.Wang","Male")) val group1 = data.groupBy(_._2) // = Map("Male" -> List(("HomeWay","Male"),("Mr.Wang","Male")),"Female" -> List(("XSDYM","Femail"))) val group2 = data.groupBy{case (name,sex) => sex} // = Map("Male" -> List(("HomeWay","Male"),("Mr.Wang","Male")),"Female" -> List(("XSDYM","Femail"))) val fixSizeGroup = data.grouped(2).toList // = Map("Male" -> List(("HomeWay","Male"),("XSDYM","Femail")),"Female" -> List(("Mr.Wang","Male")))

1 2 3 4 5 6 12.scan

scan[B >: A, That](z: B)(op: (B, B) ⇒ B)(implicit cbf: CanBuildFrom[List[A], B, That]): That

由一個初始值開始,從左向右,進行積累的op操作,這個比較難解釋,具體的看例子吧。

val nums = List(1,2,3) val result = nums.scan(10)(+) // List(10,10+1,10+1+2,10+1+2+3) = List(10,11,12,13) 1 2 13.scanLeft,scanRight

scanLeft: scanLeft[B, That](z: B)(op: (B, A) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That

scanRight: scanRight[B, That](z: B)(op: (A, B) ⇒ B)(implicit bf: CanBuildFrom[List[A], B, That]): That

scanLeft: 從左向右進行scan函式的操作,scanRight:從右向左進行scan函式的操作

val nums = List(1.0,2.0,3.0) val result = nums.scanLeft(2.0)(math.pow) // List(2.0,pow(2.0,1.0), pow(pow(2.0,1.0),2.0),pow(pow(pow(2.0,1.0),2.0),3.0) = List(2.0,2.0,4.0,64.0) val result = nums.scanRight(2.0)(math.pow) // List(2.0,pow(3.0,2.0), pow(2.0,pow(3.0,2.0)), pow(1.0,pow(2.0,pow(3.0,2.0))) = List(1.0,512.0,9.0,2.0) 1 2 3 14.take,takeRight,takeWhile

take : takeRight(n: Int): List[A] 提取列表的前n個元素 takeRight: takeRight(n: Int): List[A] 提取列表的最後n個元素 takeWhile: takeWhile(p: (A) ⇒ Boolean): List[A] 從左向右提取列表的元素,直到條件p不成立

val nums = List(1,1,1,1,4,4,4,4) val left = nums.take(4) // List(1,1,1,1) val right = nums.takeRight(4) // List(4,4,4,4) val headNums = nums.takeWhile( _ == nums.head) // List(1,1,1,1) 1 2 3 4 15.drop,dropRight,dropWhile

drop: drop(n: Int): List[A] 丟棄前n個元素,返回剩下的元素 dropRight: dropRight(n: Int): List[A] 丟棄最後n個元素,返回剩下的元素 dropWhile: dropWhile(p: (A) ⇒ Boolean): List[A] 從左向右丟棄元素,直到條件p不成立

val nums = List(1,1,1,1,4,4,4,4) val left = nums.drop(4) // List(4,4,4,4) val right = nums.dropRight(4) // List(1,1,1,1) val tailNums = nums.dropWhile( _ == nums.head) // List(4,4,4,4) 1 2 3 4 16.span, splitAt, partition

span : span(p: (A) ⇒ Boolean): (List[A], List[A]) 從左向右應用條件p進行判斷,直到條件p不成立,此時將列表分為兩個列表

splitAt: splitAt(n: Int): (List[A], List[A]) 將列表分為前n個,與,剩下的部分

partition: partition(p: (A) ⇒ Boolean): (List[A], List[A]) 將列表分為兩部分,第一部分為滿足條件p的元素,第二部分為不滿足條件p的元素

val nums = List(1,1,1,2,3,2,1) val (prefix,suffix) = nums.span( _ == 1) // prefix = List(1,1,1), suffix = List(2,3,2,1) val (prefix,suffix) = nums.splitAt(3) // prefix = List(1,1,1), suffix = List(2,3,2,1) val (prefix,suffix) = nums.partition( _ == 1) // prefix = List(1,1,1,1), suffix = List(2,3,2) 1 2 3 4 17.padTo

padTo(len: Int, elem: A): List[A]

將列表擴充套件到指定長度,長度不夠的時候,使用elem進行填充,否則不做任何操作。

val nums = List(1,1,1) val padded = nums.padTo(6,2) // List(1,1,1,2,2,2) 1 2 18.combinations,permutations

combinations: combinations(n: Int): Iterator[List[A]] 取列表中的n個元素進行組合,返回不重複的組合列表,結果一個迭代器

permutations: permutations: Iterator[List[A]] 對列表中的元素進行排列,返回不重得的排列列表,結果是一個迭代器

val nums = List(1,1,3) val combinations = nums.combinations(2).toList //List(List(1,1),List(1,3)) val permutations = nums.permutations.toList // List(List(1,1,3),List(1,3,1),List(3,1,1)) 1 2 3 19.zip, zipAll, zipWithIndex, unzip,unzip3

zip: zip[B](that: GenIterable[B]): List[(A, B)] 與另外一個列表進行拉鍊操作,將對應位置的元素組成一個pair,返回的列表長度為兩個列表中短的那個

zipAll: zipAll[B](that: collection.Iterable[B], thisElem: A, thatElem: B): List[(A, B)] 與另外一個列表進行拉鍊操作,將對應位置的元素組成一個pair,若列表長度不一致,自身列表比較短的話使用thisElem進行填充,對方列表較短的話使用thatElem進行填充

zipWithIndex:zipWithIndex: List[(A, Int)] 將列表元素與其索引進行拉鍊操作,組成一個pair

unzip: unzip[A1, A2](implicit asPair: (A) ⇒ (A1, A2)): (List[A1], List[A2]) 解開拉鍊操作

unzip3: unzip3[A1, A2, A3](implicit asTriple: (A) ⇒ (A1, A2, A3)): (List[A1], List[A2], List[A3]) 3個元素的解拉鍊操作

val alphabet = List("A",B","C") val nums = List(1,2) val zipped = alphabet zip nums // List(("A",1),("B",2)) val zippedAll = alphabet.zipAll(nums,"*",-1) // List(("A",1),("B",2),("C",-1)) val zippedIndex = alphabet.zipWithIndex // List(("A",0),("B",1),("C",3)) val (list1,list2) = zipped.unzip // list1 = List("A","B"), list2 = List(1,2) val (l1,l2,l3) = List((1, "one", '1'),(2, "two", '2'),(3, "three", '3')).unzip3 // l1=List(1,2,3),l2=List("one","two","three"),l3=List('1','2','3') 1 2 3 4 5 6 7 20.slice

slice(from: Int, until: Int): List[A] 提取列表中從位置from到位置until(不含該位置)的元素列表

val nums = List(1,2,3,4,5) val sliced = nums.slice(2,4) //List(3,4) 1 2 21.sliding

sliding(size: Int, step: Int): Iterator[List[A]] 將列表按照固定大小size進行分組,步進為step,step預設為1,返回結果為迭代器

val nums = List(1,1,2,2,3,3,4,4) val groupStep2 = nums.sliding(2,2).toList //List(List(1,1),List(2,2),List(3,3),List(4,4)) val groupStep1 = nums.sliding(2).toList //List(List(1,1),List(1,2),List(2,2),List(2,3),List(3,3),List(3,4),List(4,4)) 1 2 3 22.updated

updated(index: Int, elem: A): List[A] 對列表中的某個元素進行更新操作

val nums = List(1,2,3,3) val fixed = nums.updated(3,4) // List(1,2,3,4)