在工作中,我通常使用pyspark和Java調(diào)用spark進行數(shù)據(jù)處理??紤]到python的性能和java代碼的繁復(fù)性,以及公司特有的jar包沒有python版本,便開始使用scala進行大數(shù)據(jù)處理。下面是我在使用過程中的一些基礎(chǔ)屬性總結(jié),最后,綜合所有小知識點,給出了一個信息熵的scala版本計算函數(shù)。
Array、ArrayBuffer與List
Array數(shù)組
提供下標高效訪問(獲取或更新)指定位置的元素值。
- 內(nèi)容:不可變
- 大小:不可變
ArrayBuffer可變數(shù)組
跟Array很像,除了可以額外地從序列頭部或尾部添加或移除元素。所有的Array操作在ArrayBuffer都可用。不過由于實現(xiàn)的包裝,會稍慢一些。
- 內(nèi)容:可變
- 大小:可變
新建一個可變數(shù)據(jù)
import scala.collection.mutable.ArrayBuffer
val locations = ArrayBuffer[String]()
使用toList、toArray相互轉(zhuǎn)換:
scala> Array(1,2,3).toList
res14: List[Int] = List(1, 2, 3)
scala> List(1,2,3).toArray
res15: Array[Int] = Array(1, 2, 3)?
List
List元素不能通過賦值改變。為后進先出做了優(yōu)化,支持用::在模式匹配中取出head和tail,即支持在頭部快速添加和移除條目。但是不提供快速按下標訪問的功能,這個功能需要線性遍歷列。
- 內(nèi)容:不可變
- 大?。翰豢勺?/li>
代碼示例:
val list = List(1, 2, 3, "beijing")
// 在列表的最后追加
val newList = list :+ 6
// 在列表的頭追加
val newList02 = 6 +: list
val list = List(1,2,3)
// :: 用于的是向隊列的頭部追加數(shù)據(jù),產(chǎn)生新的列表, x::list,x就會添加到list的頭部
println(4 :: list)
//輸出: List(4, 1, 2, 3)
// .:: 這個是list的一個方法;作用和上面的一樣,把元素添加到頭部位置; list.::(x);
println( list.:: (5))
//輸出: List(5, 1, 2, 3)
// :+ 用于在list尾部追加元素; list :+ x;
println(list :+ 6)
//輸出: List(1, 2, 3, 6)
// +: 用于在list的頭部添加元素;
val list2 = "A"+:"B"+:Nil
//Nil Nil是一個空的List,定義為List[Nothing]
println(list2)
//輸出: List(A, B)
// ::: 用于連接兩個List類型的集合 list ::: list2
println(list ::: list2)
//輸出: List(1, 2, 3, A, B)
// ++ 用于連接兩個集合,list ++ list2
println(list ++ list2)
//輸出: List(1, 2, 3, A, B)
?tuple元組
當你定義一個函數(shù),想返回不同類型值時,可以使用元組。
val t = (1,23,"we are")
通過下列方式提取元組的值:
val (data_1,data_2,data_3) = t
map字典
新建一個可變字典
import scala.collection.mutable
val labelCounts: mutable.Map[String, Int] = mutable.Map()
遍歷字典的幾種方式
// 遍歷 map 的 key 和 value
for ((key, value) <- b) {
println("key is" + key + " ,value is" + value)
}
//遍歷 map 的 key 和 value
for (x <- map1){
println(x._1 + "->" + x._2)
}
// 遍歷 map 的 key
for (ele <- b.keySet) {
println("key is " + ele + " ,value is" + b.getOrElse(ele, 0))
}
// 遍歷 map 的 value
for (ele <- b.values) {
println("value is " + ele)
}
// 生成新 map ,反轉(zhuǎn) key 和 value
for ((key, value) <- b) {
yield (value, key)
}
計算信息熵,傳入一個數(shù)組和數(shù)組長度即可計算。
def CacShannonEnt(dataList: Array[String], numEntries: Int): String = {
val labelCounts: mutable.Map[String, Int] = mutable.Map()
for (featVec <- dataList) {
if (!labelCounts.contains(featVec)) {
labelCounts.put(featVec, 0)
}
labelCounts.put(featVec, labelCounts(featVec) + 1)
}
var shannonEnt = 0.0
for (value <- labelCounts.values) {
val prob = value.toDouble / numEntries
shannonEnt -= prob * (Math.log(prob) / Math.log(2))
}
shannonEnt.formatted("%.4f")
}